简体   繁体   English

如何访问/引用组件内部的组件值

[英]How to access/reference component values inside a component

Trying to build a react component where I need to control checked status of checboxes and select options when change event occurs. 尝试构建一个react组件,在其中我需要控制复选框的选中状态,并在发生更改事件时选择选项。 But I don't know how it is possible to get value of the checked checkbox(es) and set the state. 但是我不知道如何获得选中的复选框的值并设置状态。

We're using custom data-binding. 我们正在使用自定义数据绑定。 On page load, we're assigning selected value of the select, with jQuery. 在页面加载时,我们使用jQuery分配select的选择值。

  1. Programmatically changing value of the select must update matching check-boxes. 以编程方式更改select的值必须更新匹配的复选框。

  2. When user checks/unchecks a checkbox, corresponding value must be toggled on the select. 用户选中/取消选中复选框时,必须在选择项上切换相应的值。

With jQuery I would loop trough check-boxes and build array with checked values then assign this value to the select on checkbox change. 使用jQuery时,我将循环遍历复选框并构建具有检查值的数组,然后将此值分配给复选框更改中的select。 And when select change event is triggered, I would uncheck all check-boxes and check the ones matching selected items. 当选择更改事件触发时,我将取消选中所有复选框,然后选中与所选项目匹配的复选框。

This is my simplified code. 这是我的简化代码。

state = {
    items: [
            {Key: 1, Value: "A"},
            {Key: 29, Value: "Z"}
        ],
    selected: [1, 29]
}

function onSelectChange(){
    // Update checked checkboxes
}

function onCheckboxChange(){
    // Update selected options
}

<div>
    <select multiple onChange={onSelectChange} className="hidden">
        {this.state.items.map((item, i) =>
            <option value={item.Key}>{item.Value}</option>
        )}
    </select>

    <div className="checkboxes">
        {this.state.items.map((item, i) =>
            <input
                type="checkbox"
                key={i}
                checked={this.state.selected.indexOf(item.Key) >= 0}
                onChange={onCheckboxChange} />
        )}
    </div>
</div>

You would use this.setState({}) inside the event handler to update the state of a component in React. 您可以在事件处理程序中使用this.setState({})来更新React中组件的状态。 This triggers a rerender in React which allows you to query the the updated state ( this.state.selected ). 这会触发React中的重新渲染,使您可以查询更新后的状态( this.state.selected )。

Be advised that this.setState() expects an immutable object, so you should never change the previous, but always set a new state object! 请注意, this.setState()需要一个不可变的对象,因此您不应更改前一个对象,而应始终设置一个新的状态对象!

Answer to comment: 回答评论:

For selectItem: 对于selectItem:

onSelectChange = event => this.setState({selected:event.target.value})

and for checkboxes (note the prevState): 和复选框(请注意prevState):

onCheckboxChange = item => event => this.setState(({selected,...prevState})=> ({
   ...prevState,
   selected: event.target.checked? selected.concat(item): selected.filter(it=> it!== item)
}))

and usage: 和用法:

    {this.state.items.map((item, i) =>
        <input
            type="checkbox"
            key={i}
            checked={this.state.selected.indexOf(item.Key) >= 0}
            onChange={onCheckboxChange(item)} />
    )}

This has the downside that it will create a new function on each rerender, so it's better to create a custom CheckboxItem and pass the item to it and use a handleClick . 不利之处在于,它将在每次重新渲染时创建一个新函数,因此最好创建一个自定义CheckboxItem并将该项目传递给它并使用handleClick

onChange function give event where you could check whether the select box is being checked or not using this you can update your state accordingly. onChange函数提供事件,您可以使用该事件检查选择框是否被选中,您可以相应地更新状态。

function onCheckboxChange(e){
  console.log("checked", e.target.checked);
  // Then, on the basis of boolean you can update your state
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM