代码之家  ›  专栏  ›  技术社区  ›  alfredopacino

反复使用道具。儿童

  •  0
  • alfredopacino  · 技术社区  · 6 年前

    在这种情况下 item.Definition 总是一个js数组。 我想映射 项目释义 (用作 props.children )到 <Text> 要素

    <Header title={item.title}>  {item.Definition}  </Header>
    

    这是组件

    class Header extends Component {
        constructor(props) {
            super(props);
        }
        render() {
            return (
                <View {...this.props} >
                    <Text>{this.props.title}</Text>
                    <View>{
                        this.props.children ? this.props.children.map( item => <Text>{item}</Text> ) : "aaaaa";
                    }</View>
    
                </View>
            );
        }
    }
    

    我得到了一个常见的错误:“不能添加一个没有瑜伽老师的孩子……”

    3 回复  |  直到 6 年前
        1
  •  1
  •   Community datashaman    4 年前

    字符串数组或字符串永远不能是有效的节点/子节点。瑜伽节点是任何有效的节点 出生地的 widget 连接到本地UI API。

    为了解决你的问题,我会像下面这样处理

    如果 item.Definition 这是一个JS数据数组,我想我们为什么不把它传递给你的 Header 作为道具?

    您的代码应该如下所示:

    <Header title={item.title} definition ={item.Definition}/>
    

    前提是您的标题应如下所示:

    class Header extends Component {
        constructor(props) {
            super(props);
        }
        render() {
            const {definition} = this.props;
            return (
                <View {...this.props} >
                    <Text>{this.props.title}</Text>
                    <View>
                    {definition.length>0 && definition.map((item) => {
                      return (<Text>{item}</Text>) //considering item to be string.
                     })}
                    </View>
    
                </View>
            );
        }
    
        2
  •  1
  •   digit    6 年前

    我认为你有两个错误:

    1) <Text>{item}</Text> 不能是对象的类型。假设 item 如果是对象,则必须打印对象中包含的属性,而不是对象本身,例如: <Text>{item.name}</Text>

    2) "aaaaa" 不是单个字符串,必须用文本换行。 例如: <Text>aaaaa</Text>

    class Header extends Component {
       constructor(props) {
         super(props);
      }
    
      render() {
        return (
            <View {...this.props} >
                <Text>{this.props.title}</Text>
                <View>{this.props.children ?
                         this.props.children.map( item => <Text>{item}</Text> ) : 
                         <Text>aaaaa</Text>}</View>
    
            </View>
        );
      }
    }
    
        3
  •  1
  •   akhil choudhary    6 年前

    您之所以会遇到这个问题,是因为您没有在文本组件中包装静态字符串“aaaaa”。 另一个问题是,您试图在文本组件中呈现对象,这也会引发错误。所以,修复这些问题,你的组件就会工作得很好。