javascript - 使用父级 React 元素的 this.props 重复子级

标签 javascript components reactjs parent-child repeat

目前我正在创建 React 组件,我需要根据父组件的 this.props.value 重复子组件。 我正在努力寻找任何好的例子。

这是我的代码

var LiComponent = React.createClass({

render:function(){
    return(
        <div>
            <span>{this.props.label}</span>
            <span>{this.props.value}</span>
        </div>
    );
}

});

var StatsComponent = React.createClass({

    getInitialState: function(){
    return{
        value: this.props.value || []
    }
},

componentDidMount: function(){
    var data = this.state.value,
        columnName = data[0],
        data = data.slice(1),
        values = data.map(function (o) { return o.value; }),
        labels = data.map(function (o) { return o.label; });
},

shouldComponentUpdate: function(nextProps, nextState){

    var data = nextProps.value,
        labels = data.map(function (o) { return o.label; }),
        values = data.map(function (o) { return o.value; });
    return false;

},
render: function(){
    return (
        <div style={style}>
            <LiComponent>
            </LiComponent>
        </div>
    );
}

});

现在,我想根据Stats Component的this.props.value重复LiComponent。我该怎么做?

最佳答案

您可以将 LiComponent 推送到数组中,然后渲染它们。

像这样,

render: function(){
var rows = this.props.value.map(function(row) {
    //Add props to your LiComponent just as you would normally. 
    return <LiComponent />;
});
return (
    <div style={style}>
        {rows}
    </div>
);
}

关于javascript - 使用父级 React 元素的 this.props 重复子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912397/

相关文章:

javascript - 基于组件值的 vue-i18n sharedMessages 似乎不起作用

reactjs - React Router 4 - componentWillReceiveProps() 不触发

reactjs - 如何编写文档 Firestore

reactjs - 在 Material UI 中使用样式组件应用单选按钮颜色?

javascript - 从 React Native(android) 中的 .jar 文件访问方法

javascript - 用 javascript 替换部分网页 - 好吗?

javascript - 在 react-native 中处理首次使用的用户

java - JPanel 上的组件未以原始大小显示

Javascript createElement 没有结束标签

javascript - Vue - 尝试以数字形式发出值并在发出时获取字符串