首页 > 解决方案 > 在 React 中获取事件目标的兄弟值的好方法是什么?

问题描述

function NewItem(props) {
    return (
        <div>
            <input
                id = "content"
                placeholder = "add a new item..."
            />
            <input
                id = "score"
                placeholder = "score(points per hour)"
            />
            <button
                onClick = {
                    (e) => props.onAddItem(e)
                }
            >
                add
            </button>
        </div>
    );
}

按钮单击处理程序是在父类中实现的,我想要做的是当我单击“添加”时,父类可以获取这两个输入的值,以便它可以在其“ itemList”状态。有什么好方法可以让我获得价值吗?我知道我可以操纵 DOM 来做到这一点,但我想这不是一个好方法。

下面是父类的点击处理程序和渲染方法:

handleAddItem(e) {
    const newList = this.state.itemList;
    const itemCount = this.state.itemCount;
    newList.unshift({
        itemInfo: {
            content: ,
            score: ,
            time: ,
        }
        key: itemCount,
        index: itemCount,
    });
    this.setState({
        itemList: newList,
        itemCount: itemCount + 1,
    });
}


render() {
    return (
        <div id = "todo">
            <NewItem
                onAddItem = {
                    (e) => this.handleAddItem(e)
                }
            />
            <ItemList
                itemList = { this.state.itemList }
                onClick = {
                    (e) => this.handleDeleteItem(e)
                }
            />
        </div>
    )
}

标签: reactjs

解决方案


您可能想查看参考资料或“参考资料”。我通常避免尝试使用它们,但有时它只是处理问题的一种更清洁的方法。

这是一个可能对您有所帮助的片段。

import React from 'react'

class TestComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      controlledValue: 'controlled'
    }

    this._handleControlledChange = this._handleControlledChange.bind(this)
  }

  _handleControlledChange(e) {
    this.setState({
      controlledValue: e.target.value
    })
  }

  render(){
    return (
            <div>
            {/* Bind this to 'this.field1' */}
            <h3>Function Binding</h3>
            <input ref={f => this.field1 = f} />
            {/* bind this to this.refs.field2 */}
            <h3>Bind to Refs</h3>
            <input ref='field2' />

            <h3>Controlled Component</h3>
            <input 
              value={this.state.controlledValue} 
              onChange={this._handleControlledChange}
            />

            <button 
              onClick = {
                e => {
                  let field1Value = this.field1.value
                  let field2Value = this.refs.field2.value

                  alert('Field 1 ' + field1Value + '\n Field 2 ' + field2Value + '\nConrolled: ' + this.state.controlledValue )
                } 
              }
            >
            Ref test
            </button>

          </div>
    )
  }
}

基本上发生的事情是我将组件绑定到类,以便以后可以引用它。通常 React 代码将依赖于状态并且不允许组件管理自己,但有时这是您想要的行为(一次性形式或您不想管理状态的东西)。

希望这会有所帮助。我演示了您可能希望控制组件的三种主要方式。查看https://material-ui.com/等项目和教程以获取更多示例。

@wdm 的表单是一个聪明的解决方案,我没有使用过,但我喜欢它。


推荐阅读