【问题标题】:How do I access dynamically generated/rendered children within a React component?如何访问 React 组件中动态生成/渲染的子级?
【发布时间】:2021-02-24 23:27:13
【问题描述】:

首先,我有一个类组件(在本例中,我们称它为 DynamicComponent),它不包含子组件,但会动态生成 HTML。 DynamicComponent 的示例渲染函数:

render() {
    return (
        <div>
            <input type="text" name="first" />
            <input type="text" name="last" />
        </div>
    );
}

在一个单独的/父组件(我称之为&lt;Form&gt;)中,我循环遍历子元素并搜索元素,以便在表单上注册它们并对其执行验证。这里的问题是,当它到达函数底部的递归部分(child.type === 'DynamicComponent')时,child.props.children 是未定义的(意料之中,因为我没有将任何子项作为道具传递给 DynamicComponent)。我将如何从运行此getChildInputs 函数的父组件中获取动态呈现的字段?简化函数(它是一个累加函数,传入.reduce()):

getChildInputs = (acc, child) => {
    // Find form elements and make note of their validation requirements
    if (
        typeof child.type === 'string' &&
        (child.type === 'input' || child.type === 'textarea')
    ) {
        acc[child.props.id] = {
            valid: true,
            touched: false,
            rules: [],
            invalidRules: [],
        };
        if (child.props.required) {
            acc[child.props.id].rules.push('required');
        }
        if (child.props.type === 'email') {
            acc[child.props.id].rules.push('email');
        }
        if (typeof child.props.match !== 'undefined') {
            acc[child.props.id].rules.push('match');
            acc[child.props.id].match = child.props.match;
        }
        if (typeof child.props.maxLength !== 'undefined') {
            acc[child.props.id].rules.push('maxLength');
            acc[child.props.id].maxLength = child.props.maxLength;
        }
    }
    // Make it a recursive search
    if (React.isValidElement(child)) {
        React.Children.toArray(child.props.children).reduce(Form.getChildInputs, acc);
    }
    return acc;
}

Parent() 组件渲染函数:

render() {
    return (
        <div>
            <DynamicComponent />
            <AnotherChildComponent>
                <input type="text" name="input1" />
                <input type="text" name="input2" />
            </AnotherChildComponent>
        </div>
    );
}

因此,在这种情况下,getChildInputs 函数将简化为包含 input1input2 元素的数组,但它不会拾取 firstlast 元素。有没有办法让我获得元素/组件的实际子项,而不仅仅是依赖 props.children

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我认为你可以在这里使用 ref。在您的父组件中创建 ref 并将其转发给您的孩子。之后,您可以访问调用 ref.current.children 的子组件的子组件。这是一些代码示例,希望您能够根据您的特定示例对其进行调整:

    class App extends React.Component {
      constructor(props) {
        super(props)
        this.ref = createRef();
        this.handleClick = this.handleClick.bind(this)
      }
    
      handleClick() {
        console.log(this.ref.current.children)
        // would console log 
        // HTMLCollection {0: HTMLInputElement, 1: HTMLInputElement, length: 2, item: ƒ item(), namedItem: ƒ namedItem()…}
        // 0: 
        // <input type="text" name="first"></input>
        // 1: 
        // <input type="text" name="last"></input>
        // length: 2
        // item: ƒ item() {}
        // namedItem: ƒ namedItem() {}
        // <constructor>: "HTMLCollection"
      }
    
      render() {
        return (
          <div className="App">
            <Dynamic ref={this.ref}  />
            <button onClick={this.handleClick}>A</button>
          </div>
        );
    
      }
    
    }
    
    
    const Dynamic = React.forwardRef((props, ref) => {
      return (
        <div ref={ref}>
            <input type="text" name="first" />
            <input type="text" name="last" />
        </div>
      )
    })
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2015-09-07
      • 2014-12-18
      • 1970-01-01
      • 2021-09-07
      • 2023-03-20
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多