reactjs - 如何在 Parent 的孩子中使用 ref 访问 Child - React@latest
问题描述
此代码示例是结构的最小表示
我们将所有其他组件分组的主要组件:
<Form>
<FormGroup>
<RadioGroup>
<RadioButton/>
<RadioButton/>
</RadioGroup>
</FormGroup>
<FormGroup>
<TextInput />
</FormGroup>
<Button>Submit Form</Button>
</Form>
目标是创建对每个in或每个in或 even的引用,所以让我们进一步了解组件,现在 Form 和 FormGroup 是渲染子组件的空组件:TextInput
FormGroup
RadioButton
RadioGroup
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>
);
}
};
解决方案
如果您正在使用表单,我建议您使用 react-hook-form。 反应挂钩形式
推荐阅读
- c# - 寻找优雅的方式来获取子字符串
- html - 当我将边框设置为 0 时,为什么我的输入周围有边框?(CSS)
- mysql - 查询显示错误的结果
- python-3.x - 发现样本数量不一致的输入变量:[159, 40]
- php - move_uploaded_file() 无法将文件移动到 Google App Engine 上的 Google Storage (php 7.2)
- php - json_encode 转义字符 '<'
- android - 在 Android-Image-Cropper 中设置 ColorFilter
- sql-server - SQL Server 计算列中的条件
- r - R- Shiny - 如何更改饼图中图例的颜色?
- android - 使用 Facebook 登录时在 Firebase 中创建新用户