我是 React 和 JavaScript 的新手。
我有一个 Menu 组件,它呈现一个动画 onClick
,然后将应用程序重定向到另一个路径,/coffee
。
我想将单击(选择)的值传递给函数 this.gotoCoffee
并更新 this.state.select
,但我不知道如何,因为我在同一 onClick
事件中映射 this.state.coffees
中的所有项目。
我如何做到这一点并将 this.state.select
更新为点击值?
我的代码:
class Menus extends Component{
constructor (props) {
super(props);
this.state = {
coffees:[],
select: '',
isLoading: false,
redirect: false
};
};
gotoCoffee = () => {
this.setState({isLoading:true})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
}
renderCoffee = () => {
if (this.state.redirect) {
return (<Redirect to={`/coffee/${this.state.select}`} />)
}
}
render(){
const data = this.state.coffees;
return (
<div>
<h1 className="title is-1"><font color="#C86428">Menu</font></h1>
<hr/><br/>
{data.map(c =>
<span key={c}>
<div>
{this.state.isLoading && <Brewing />}
{this.renderCoffee()}
<div onClick={() => this.gotoCoffee()}
<strong><font color="#C86428">{c}</font></strong></div>
</div>
</span>)
}
</div>
);
}
}
export default withRouter(Menus);
我试过像这样传递值:
gotoCoffee = (e) => {
this.setState({isLoading:true,select:e})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
console.log(this.state.select)
}
像这样:
<div onClick={(c) => this.gotoCoffee(c)}
左右:
<div onClick={(event => this.gotoCoffee(event.target.value}
但是 console.log(this.state.select)
两次尝试都显示“undefined
”。
看来我正在传递带有“c”的 Class
。
浏览器在重定向的 uri 上准确地向我显示:
http://localhost/coffee/[object%20Object]
现在,如果我将映射的“c”传递给 {this.renderCoffee(c)}
,这不是一个 onClick
事件,我就会设法传递数组项。
但我需要传递的不是对象,而是单击值“c”到 this.gotoCoffee(c)
,然后更新 this.state.select
。
我该如何解决这个问题?
最佳答案
您可以将元素的 index
传递给 gotoCoffee
并在 render
中关闭。然后在 gotoCoffee
中,只需访问该元素作为 this.state.coffees[index]
。
gotoCoffee = (index) => {
this.setState({isLoading:true, select: this.state.coffees[index]})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
}
render(){
const data = this.state.coffees;
return (
<div>
<h1 className="title is-1"><font color="#C86428">Menu</font></h1>
<hr/><br/>
{data.map((c, index) =>
<span key={c}>
<div>
{this.state.isLoading && <Brewing />}
{this.renderCoffee()}
<div onClick={() => this.gotoCoffee(index)}
<strong><font color="#C86428">{c}</font></strong></div>
</div>
</span>)
}
</div>
);
}
}
关于javascript - React - 改变 this.state onClick 用 array.map() 呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581731/