我创建了一个组件。代码可以在这里看到: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>
}
}
关于javascript - 添加来自另一个 react 组件的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43089966/