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

标签 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 组件中增加值(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/

相关文章:

javascript - ReactJs 中 JSON 的 GridView 格式

javascript - 通过 JSON 接收数据后的可编辑文本框

javascript - 使用变量名称将子对象添加到 JavaScript 对象

javascript - js如何在字符串上使用splice?

javascript - React 更新后状态类型发生变化

javascript - 尝试根据筛选器选择使用字符串值填充数组,并通过将数组与记录属性的字符串值进行比较来筛选记录

javascript - 至少需要 2 次刷新才能加载页面

Javascript 通过操作确认?

javascript - 单击显示时如何始终显示隐藏的 div,在其他 div 之上

javascript - setState 在 React 中的 setInterval 中不起作用