Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从另一个组件添加值_Javascript_Reactjs - Fatal编程技术网

Javascript 从另一个组件添加值

Javascript 从另一个组件添加值,javascript,reactjs,Javascript,Reactjs,我创建了一个组件。代码可以在这里看到: 如何从Addnews组件添加值 class Addnew extends React.Component { constructor () { super(); } saveit () { const currentItems = this.state.inItems, newVal = this.refs.inputVal.value; currentIte

我创建了一个组件。代码可以在这里看到:

如何从Addnews组件添加值

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 Component:

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>
 )
}
并添加新组件:

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>
    }
}

下面是修改后的代码:

您可以添加更多解释吗?您可以使用redux或类似工具。非常感谢:+1:
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>
    }
}