Reactjs 呈现一个字符串数组的状态。推送后,获取[对象]
当我按下一个按钮时,应该会按下一条消息(str),它不工作。 它显示[对象] 以下是我的简单代码:Reactjs 呈现一个字符串数组的状态。推送后,获取[对象],reactjs,Reactjs,当我按下一个按钮时,应该会按下一条消息(str),它不工作。 它显示[对象] 以下是我的简单代码: class Body extends Component { constructor(props){ super(props) this.state = { news: ["chao","chao"] } this.pushNews = this.pushNews.bind(this) } pushN
class Body extends Component {
constructor(props){
super(props)
this.state = {
news: ["chao","chao"]
}
this.pushNews = this.pushNews.bind(this)
}
pushNews(content){
this.setState({news: [...this.state.news, content]})
}
渲染(
{返回(
添加新闻!
{this.state.news.map((项目,i)=>(
{item.toString()}
)
}
)
我得到:[对象]
我应该看到输入“meesage”正在呈现:(将onClick调用更改为如下内容:
onClick={() => this.pushNews("message")}
您不需要在函数上调用
bind
来发送数据,并且您的呈现
函数的格式不正确:
render(){
return(
<div>
<Button size = "small" onClick = {() => this.pushNews("message")} > AddNews!</Button>
{this.state.news.map((item, i) => <div key={i}>{item.toString()}</div>)}
</div>
)
}
还有一个更简单的onClick
:onClick={this.pushNews(“message”)}
这将产生完全相同的结果,并允许您删除构造函数中的绑定您可以格式化渲染函数吗?此语法不会编译
render(){
return(
<div>
<Button size = "small" onClick = {() => this.pushNews("message")} > AddNews!</Button>
{this.state.news.map((item, i) => <div key={i}>{item.toString()}</div>)}
</div>
)
}
pushNews = content => event => {