这个代码示例是对结构的最小化表示
主要组件,我们将所有其他组件分组。
<Form>
<FormGroup>
<RadioGroup>
<RadioButton/>
<RadioButton/>
</RadioGroup>
</FormGroup>
<FormGroup>
<TextInput />
</FormGroup>
<Button>Submit Form</Button>
</Form>
我们的目标是创建一个 参考 对每一个 TextInput
在 FormGroup
或对每个 RadioButton
在 RadioGroup
甚至 FormGroup
,所以让我们再往下看组件,目前Form和FormGroup是空的组件,渲染子组件。
const Form: React.FunctionComponent<Props> = ({ children }) => {
return (
<form>
{children}
</form>
);
};
const FormGroup: React.FunctionComponent<Props> = ({ children }) => {
// WE WANT TO ACCESS REF HERE, with React.Children.map every child's ref is always null
return (
{children}
);
};
为了简单起见 RadioGroup
也只是呈现出孩子
const RadioGroup: React.FunctionComponent<Props> = ({ children }) => {
// WE WANT TO ACCESS REF HERE, with React.Children.map every child's ref is always null
return (
{children}
);
};
我们正在进入正题,我们要创建一个引用的Child,在这个例子中是 RadioButton
组成部分
class RadioButton extends Component<{props}, state> {
this.state = {
inputRef: React.createRef()
};
handleClick() {
WE CAN ACCESS THE REF HERE
// this.state.inputRef.current
}
render() {
return (
<div> // putting the ref here also doesnt work in parent components
<label>
<input
ref={this.state.inputRef}
onChange={() => this.handleClick()}
/>
</label>
</div>
);
}
};
如果你使用form,我建议你使用react-hook-form。react-hook-form