Reactjs 如何使用父项中的ref访问子项';儿童-React@latest
此代码示例是结构的最小表示形式 我们对所有其他组件进行分组的主要组件:Reactjs 如何使用父项中的ref访问子项';儿童-React@latest,reactjs,parent-child,react-props,ref,Reactjs,Parent Child,React Props,Ref,此代码示例是结构的最小表示形式 我们对所有其他组件进行分组的主要组件: <Form> <FormGroup> <RadioGroup> <RadioButton/> <RadioButton/> </RadioGroup> </FormGroup> <FormGroup> <Text
<Form>
<FormGroup>
<RadioGroup>
<RadioButton/>
<RadioButton/>
</RadioGroup>
</FormGroup>
<FormGroup>
<TextInput />
</FormGroup>
<Button>Submit Form</Button>
</Form>
现在我们进入重点,我们想要创建一个引用的子项,在本例中是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>
);
}
};
class单选按钮扩展组件{
此.state={
inputRef:React.createRef()
};
handleClick(){
我们可以在这里访问REF
//this.state.inputRef.current
}
render(){
返回(
//在父组件中,将ref放在这里也不起作用
this.handleClick()}
/>
);
}
};
如果您正在使用表单,我建议您使用react hook表单。
如果您使用表单,我建议您使用react hook表单。
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}
);
};
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}
);
};
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>
);
}
};