我刚接触到ReactJS,我正在开发一个可过滤的画廊,但现在我看了一个在ReactJS中思考的例子,我看到他们正在为每个组件构建不同的类。我没有这样做,但现在我试图这样做,首先我的代码看起来像这样:`
var SearchBar = React.createClass({
getInitialState() {
return { text:'', array: this.props.array};
},
handleChange(event) {
var array = this.filterList(event.target.value);
this.setState({ text: event.target.value, array: array });
return this.state.text;
},
render() {
var arrayComponents = this.state.array.map(function(photo) {
return <li className="photo photo-name">{photo.name} <img className="photo" src={photo.link}/></li>;
});
return <div>
<h1>Hello, {this.props.name}</h1>
<p>{this.state.text}</p>
<input type="text" onChange={this.handleChange} />
<ul>
{arrayComponents}
</ul>
</div>;
},
filterList (filterText) {
var updatedList = this.props.array,
filterTextLength = filterText.length;
return updatedList.filter(function(item){
var splitName = item.name.toLowerCase().slice(0, filterTextLength);
var lowerCaseFilterText = filterText.toLowerCase();
return splitName === lowerCaseFilterText;
});
}
});
现在我想创建另一个ImageList类,它必须包含var arrayComponents
但如果我这样做:
var ImageList = React.createClass({
render() {
var arrayComponents = this.props.array.map(function(photo) {
return <li className="photo photo-name">{photo.name} <img className="photo" src={photo.link}/></li>;
});
<ul>
{arrayComponents}
</ul>
}
})
并且在render函数中添加<ImageList array={array}/>
而不是<ul>{arrayComponent}</ul>
,它会引发错误Cannot read property 'map' of undefined
如何将数组状态传递给该ImageList类。
这是一个codepen:LINK
答案 0 :(得分:1)
我在您的代码中进行了以下更改:http://codepen.io/PiotrBerebecki/pen/zKRAGZ
1)将数组的状态传递给ImageList
类
<ImageList array={this.state.array} />
2)在return
<{1}}方法中添加render
语句
ImageList
3)使用map方法时,将// Add return
return (
<ul>
{arrayComponents}
</ul>
);
属性添加到key
标记:
li
反应文档:https://facebook.github.io/react/docs/multiple-components.html#dynamic-children
答案 1 :(得分:0)
您需要传递数组的当前状态。因此,您的组件声明应如下所示:
<ImageList array={this.state.array}/>
答案 2 :(得分:0)
var ImageList = React.createClass({
render() {
var arrayComponents = this.props.array.map(function(photo) {
return <li className="photo photo-name">{photo.name} <img className="photo" src={photo.link}/></li>;
});
<ul>
{arrayComponents}
</ul>
}
})
你应该说:
return (<ul>
{arrayComponents}
</ul>)
其次,当您使用动态生成的代码时,您应该为其添加key
道具:
var arrayComponents = this.props.array.map(function(photo) {
return <li key={SOME_KEY} className="photo photo-name">{photo.name} <img className="photo" src={photo.link}/></li>;
});
第三,在你的代码中你说:
<ImageList array={array}/>
您正在引用全局变量array
(您在代码的顶部声明它),您的意思是:
<ImageList array={this.state.array}/>