【发布时间】:2019-03-24 04:29:50
【问题描述】:
只注册了一个按键,然后输入失去焦点,但是我可以单击返回组件并添加...一个字符。状态已更新。
由于子组件是无状态的,我假设仅将处理程序作为文档中描述的道具向下传递就足够了,但是从更改方法的绑定到添加构造函数的所有内容都产生了相同的结果。我通常可以在网站上找到答案,但这次没有运气。
const list = [
{
id : 0,
title : "Went well",
showCard : false,
cards : [],
color : "pink"
},
{
id : 1,
title : "To Improve",
showCard : false,
cards : [],
color : "yellow"
},
{
id : 2,
title : "Action Items",
showCard : false,
cards : [],
color : "blue"
}
]
class App extends Component {
state = {list : list, usrInpt : ""}
handleChange = e => {this.setState({usrInpt:e.target.value})}
add = e => {
e.preventDefault()
let updatedList = this.state.list.map(obj => {
if(obj.id == e.target.id)
this.state.list[obj.id].cards.push(this.state.usrInpt)
return obj
})
console.log("uL",updatedList)
this.setState({list:updatedList})
//this.setState(this.state.list[e.target.id].cards = [...this.state.list[e.target.id].cards,"pp"])
}
render() {
return (
<div className="App">
<h2>Metro Board</h2>
<ul className="container">
{this.state.list.map((item) =>
<List key={(Math.random() * 1)} text={item.title}
id={item.id} cards={item.cards} color={item.color}
usrInpt={this.state.usrInpt} add={this.add} handleChange={this.handleChange}/>
)}
</ul>
</div>
)
}
}
const List = (props) =>{
return(
<li>
<h3>{props.text}</h3>
<ul className="stack">
<li><button id={props.id} type="button" className="block" onClick={e =>props.add(e)}>+</button></li>
{props.cards.map((card,i)=> {
console.log("card",card)
return <ListItem key={(Math.random() * 1)}
idx={i}
color={props.color}
handleChange={props.handleChange}
usrInpt={props.usrInpt}/>
})}
</ul>
</li>
)
}
const ListItem = (props) =>{
console.log("card props and value",props)
return <li>
<div className="card" style={{backgroundColor: props.color}}>
<textarea type="text"
className="card"
placeholder="Enter text here"
value={props.usrInpt}
onChange={e => props.handleChange(e)}>
</textarea>
<div><a className="ltCtl" href="./logo" onClick={e => console.log(e)}><</a>
<a className="clCtl" href="./logo" onClick={e => console.log(e)}>x</a>
<a className="rtCtl" href="./logo" onClick={e => console.log(e)}>></a>
</div>
</div>
</li>
}
List && ListItem 都是单独的文件...任何帮助都会很棒。谢谢。
【问题讨论】:
-
如果你能提供一个更简单的例子,只用很少或没有多余的代码来说明你的问题,它会让其他人更容易帮助你。
-
随机生成密钥可能会导致渲染周期出现问题。看起来您的数据已经具有唯一 ID,因此请在映射数组时尝试使用
key={item.id} -
@miyu 我测试了这个理论,这不是问题的根源。
-
@miyu 你说得对,我看到你的回复,并没有自己测试。我为此道歉,以后不会再发生了。谢谢。
标签: javascript reactjs