我想在列表中添加一个字符串,并且有一个CounterComponent与分开工作的字符串,我HelloWordComponent为Microsoft设置1,为FaceBook设置2,为React设置3;当我将“ yahoo”添加到列表的第一行时,“ yahoo”的计数器设置为1,并且反应变为0。
我知道我必须使用唯一的密钥,并且我认为它{name}是合格的,但是我不知道key = {name}确切地在哪里使用?
class HelloWordComponent extends React.Component {
render() {
return <div>{this.props.name}</div>
}
}
class Counter extends React.Component {
constructor(){
super()
this.onPlusClick = this.onPlusClick.bind(this)
this.state = {count : 0}
}
onPlusClick(){
this.setState(prevState => ({count: prevState.count + 1}))
}
render(){
return <div>
{this.state.count}
<button onClick = {this.onPlusClick}>+</button>
</div>
}
}
class App extends React.Component{
constructor(){
super()
this.addName = this.addName.bind(this)
this.state = {
name: "Sara",
list:['Microsoft', 'FaceBook', 'React']
}
}
addName(){
this.setState(prevState =>({list: ['Yahoo', ...prevState.list]}))
}
render(){
return (
<div >
{this.state.name}
{this.state.list.map(name =>{
return <div>
<HelloWordComponent key = {name} name = {name}/>
<Counter/>
</div>
})}
<br/>
<button onClick= {this.addName}>add a Name</button>
</div>
);
}
}
ReactDOM.render(<App/>,document.getElementById("app"));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"> </div>Run Code Online (Sandbox Code Playgroud)
我找到了解决问题的正确方法,我必须key = {name}在父根元素中 设置唯一键(),<div key = {name}>以便render方法更改为:
render(){
return (
<div >
{this.state.name}
{this.state.list.map(name =>{
return <div key = {name}>
<HelloWordComponent name = {name}/>
<Counter/>
</div>
})}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |