【发布时间】:2016-09-29 23:52:39
【问题描述】:
上下文
我正在尝试将输入值字段 (conditionTitle) 从 React Stateless 子组件 (AddConditionSelect) 传递到将保存我的状态的父组件 (AddConditionDashboard)。
问题
我遵循React documentation 中显示的模型,但他们使用的是 refs,这仅在组件是有状态的情况下才有效。我不想在子组件中设置任何状态,但仍然能够访问父组件中的输入。
在当前的形式中,我收到了一个警告,即无法为无状态函数组件提供 refs,从而导致 props 为 null 且未定义。
父组件:
import AddConditionSelect from '../containers/AddConditionSelect.js';
class AddConditionDashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
conditionTitle: '',
conditionType: ''
};
}
handleUserInput({conditionTitleInput}) {
this.setState({
conditionTitle:conditionTitle
})
}
render() {
const {error, segmentId} = this.props;
return (
<div>
<AddConditionSelect segmentId={segmentId} conditionTitle={this.state.conditionTitle} onUserInput={this.handleUserInput} />
<PanelFooter theme="default">
<Button backgroundColor="primary" color="white" inverted={true} rounded={true} onClick={(event) => this.onSubmit(event)}>
Next Step
</Button>
</PanelFooter>
</div>
);
}
}
export default AddConditionDashboard;
子组件:
class AddConditionSelect extends React.Component {
onInputChange: function() {
this.props.onUserInput(
this.refs.conditionTitleInput.value,
)
},
render() {
const {error} = this.props;
return (
<div>
<Panel theme="info">
<Divider />
Please enter a name {error ? <Message inverted={true} rounded={true} theme="error">{error}</Message> : null}
<Input value={this.props.conditionTitle} ref="conditionTitleInput" label="" type="text" buttonLabel="Add Condition" name="add_segment" onChange={this.onInputChange} placeholder="Condition Title"/>
</Panel>
</div>
);
}
}
export default AddConditionSelect;
【问题讨论】:
-
您能向我们展示您的输入组件吗?这会有所帮助。
-
输入组件只是一个 Rebass 组件 - jxnblk.com/rebass/#Input
标签: javascript reactjs ecmascript-6