我有一个名为<MultiSelect />
的组件。在组件中包含它自己的状态。我需要从中获取价值到父容器。我该怎么做?
MultiSelect:
state = {
multi: null,
}
handleChange = (name) => (value) => {
this.setState({
[name]: value,
})
}
return (
<div className={classes.root}>
<NoSsr>
<Select
classes={classes}
styles={selectStyles}
textFieldProps={{
label: 'Label',
InputLabelProps: {
shrink: true,
},
}}
options={diagnosticCodes}
components={components}
value={this.state.multi}
onChange={this.handleChange('multi')}
placeholder="Select multiple countries"
isMulti
/>
</NoSsr>
</div>
)
我要在“父容器”中输入{this.state.multi}
的值。我无法从外部定义状态并处理onChange事件,因为<MultiSelect />
位于map
中,因此,如果我尝试从外部处理更改,则它们都将处于相同状态。
答案 0 :(得分:0)
您可以将父组件上存在的方法传递给MultiSelect
组件
ParentComponent.js:
class ParentComponent extends React.Component {
constructor() {
this.handleSelect = this.handleSelect.bind(this);
}
handleSelect(selectedValue) {
//handle selected value
}
render() {
return <MultiSelect handleSelect={this.handleSelect} />
}
}
MultiSelectComponent.js
handleChange = (name) => (value) => {
this.setState({
[name]: value,
}, () => this.props.handleSelect(this.state.multi)); //Call the method in the callback of setState
}