【发布时间】:2020-06-03 15:18:57
【问题描述】:
此代码示例是结构的最小表示
我们将所有其他组件分组的主要组件:
<Form>
<FormGroup>
<RadioGroup>
<RadioButton/>
<RadioButton/>
</RadioGroup>
</FormGroup>
<FormGroup>
<TextInput />
</FormGroup>
<Button>Submit Form</Button>
</Form>
目标是为FormGroup 中的每个TextInput 或RadioGroup 甚至FormGroup 中的每个RadioButton 创建一个引用,所以让我们进一步了解组件,目前 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>
);
}
};
【问题讨论】:
标签: reactjs parent-child react-props ref