【发布时间】:2018-10-23 21:54:50
【问题描述】:
是否有任何入口点可以在子树中找到实际输入 (child.type === 'input')?
class MyForm extends React.Component {
parseChildren(children) {
React.Children.forEach(children, child => {
if (child) {
console.log('type', child.type);
if (child.props && child.props.children) {
this.parseChildren.bind(this)(child.props.children);
}
}
});
}
componentWillMount() {
this.parseChildren(this.props.children);
}
componentDidMount() {
this.parseChildren(this.props.children);
}
render() {
return <form>{this.props.children}</form>;
}
}
class MyInput extends React.Component {
render() {
return (
<p>
My beautiful input <input {...this.props} />
</p>
);
}
}
ReactDOM.render(
<MyForm>
<MyInput type="text" />
</MyForm>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
【问题讨论】:
-
你想检查一个孩子是否是
MyInput类的实例吗? -
没有。我想检查在子渲染树的深处是否有输入组件(反应包装器围绕 dom 输入而不是 dom 节点)。