遍历props.children

时间:2018-12-04 01:04:43

标签: react-native

在这种情况下,item.Definition始终是一个js数组。 我想将item.Definition(用作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>
        );
    }
}

我得到通常的错误:“无法添加没有YogaNode的孩子。”

3 个答案:

答案 0 :(得分:1)

字符串数组或字符串永远不能是有效的Yoga节点/子代。 Yoga节点是指任何有效的本地from collections import namedtuple EXAMPLE_DATA = [ ['time', 'age', 'height', 'width', 'ethnicity', 'religion'], ['18:42:11', '61', '153.9615', '0.8', 'Mixed', 'None'], ['18:35:00', '34', '116.4253333', '10.17', 'Mixed', 'None']] def display_data(example_func): Record = namedtuple('Record', example_func[0]) for row in example_func[1:]: print('Time: {time}\n' 'Age: {age}\n' 'Height: {height}\n' 'Ethnicity: {ethnicity}\n'.format(**Record(*row)._asdict())) display_data(EXAMPLE_DATA) 被桥接以响应本机UI API的节点。

要解决您的问题,我将按照以下方式处理

如果我假设def display_data(example_func): Record = namedtuple('Record', example_func[0]) for rec in (Record(*row) for row in example_func[1:]): print(f'Time: {rec.time}\n' f'Age: {rec.age}\n' f'Height: {rec.height}\n' f'Ethnicity: {rec.ethnicity}\n') 是一个JS数据数组,那为什么不将它作为道具传递给您的widget

您的代码应如下所示:

item.Definition

提供的标题如下:

Header

答案 1 :(得分:1)

我认为您在这里有2个错误:

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>
    );
  }
}

答案 2 :(得分:1)

由于没有在Text组件中包装静态字符串“ aaaaa”,因此出现了此问题。 另一个问题是您试图在文本组件中渲染对象,这也会引发错误。因此,修复这些问题,您的组件将正常工作。