从另一个反应组件添加值

时间:2017-03-29 09:46:04

标签: javascript reactjs

我创建了一个组件。代码可以在这里看到: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组件中添加值?

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

1 个答案:

答案 0 :(得分:1)

您必须在添加组件中呈现 Addnew 组件。

然后将添加功能作为道具传递给 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