gpt4 book ai didi

javascript - 添加来自另一个 react 组件的值

转载 作者:行者123 更新时间:2023-12-03 04:41:01 26 4
gpt4 key购买 nike

我创建了一个组件。代码可以在这里看到:http://codepen.io/anon/pen/zZmyyd

class Add extends React.Component  {
constructor () {
super();
this.state = {
inItems: ["aaa", "bbb", "ccc", "ddd"]
}
this.state.items= this.state.inItems;
}


add () {
const currentItems = this.state.inItems,
newVal = this.refs.inputVal.value;
currentItems.push(newVal);
this.setState({
items: currentItems,
value: newVal
});
}

render () {
return (
<div>
<input type="text" ref="inputVal"/>
<button type="button" onClick={this.add.bind(this)}>Add</button>
<List items= {this.state.items} />
</div>
)
}
}

class List extends React.Component {
render () {
return (
<ul>
{
this.props.items.map(function(item) {
return <li key={item}>{item}</li>
})
}
</ul>
)
}
}


ReactDOM.render(
<Add />,
document.getElementById('root')
);

如何从 Addnews 组件中增加值(value)?

class Addnew extends React.Component {
constructor () {
super();
}

saveit () {
const currentItems = this.state.inItems,
newVal = this.refs.inputVal.value;
currentItems.push(newVal);
this.setState({
items: currentItems,
value: newVal
});
}

render () {
return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
}
}

最佳答案

您必须在 Add 组件中渲染 Addnew 组件。

然后将add函数作为props传递给Addnew组件:

render () {
return (
<div>
<input type="text" ref="inputVal"/>
<button type="button" onClick={this.add.bind(this)}>Add</button>
<List items= {this.state.items} />
<Addnew add={this.add.bind(this)} />
</div>
)
}

在 Addnew 组件中:

class Addnew extends React.Component {
constructor () {
super();
}

saveit () {
this.props.add();
}

render () {
return <button type="button" onClick={this.saveit.bind(this)} ref="inputVal">Add Value from here</button>
}
}

这是修改后的代码:http://codepen.io/anon/pen/OpBdpV?editors=0010#0

关于javascript - 添加来自另一个 react 组件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43089966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com