我試圖用React創建待辦事項列表,並且已經非常接近。當我單擊按鈕時,我將<li>
元素添加到dom中,但是我將輸入字段中的文本設置爲所有<li>
s。我對React很陌生,有點困惑。將唯一列表項添加到ReactJS中的DOM
我該怎麼做?見代碼,並鏈接到codepen:
var ListContainer = React.createClass({
getInitialState: function() {
return {
numChildren: 0,
text: null
};
},
onAddChild: function() {
var inputValue = document.getElementById('itemAdder').value;
console.log(inputValue);
this.setState({
numChildren: this.state.numChildren + 1,
text: inputValue
});
},
render: function() {
var children = [];
for (var i = 0; i < this.state.numChildren; i++) {
children.push(<Item key={'item_' + i} number={i} text={this.state.text}/>);
};
return (
<List addChild={this.onAddChild}>
{children}
</List>
);
}
});
var List = React.createClass({
render: function() {
return (
<div id="listContainer">
<p><input type="text" name="itemAdder" id="itemAdder" /></p>
<p><button type="button" onClick={this.props.addChild}>Add another item</button></p>
<ul>
{this.props.children}
</ul>
</div>
);
}
});
var Item = React.createClass({
render: function() {
var key = this.props.index;
return (
<li>{this.props.text}</li>
);
}
});
var App = React.createClass({
render: function() {
return (
<div id="main" className="page-wrap">
<ListContainer />
</div>
);
}
});
ReactDOM.render(
<App/>,
document.getElementById('app')
);
謝謝。完美工作 –
高興地幫助:) – Swapnil