【问题标题】:Find html node in react component for initialization after component mounts. Instance from JSX.Element creation在组件挂载后在 react 组件中找到 html 节点进行初始化。来自 JSX.Element 创建的实例
【发布时间】:2021-05-08 09:00:38
【问题描述】:

我像这样在我的组件中初始化具体化下拉列表:

componentDidMount() {
    const selects = document.querySelectorAll('select');
    selects.forEach(select => {
      M.FormSelect.init(select, {
        dropdownOptions: {
          //...options not relevant
        }
      });
    });
    // console.log('select count: ', selects.length);
  }

只要我的组件的所有下拉列表都是组件本身的一部分,那就可以了,这意味着没有条件渲染的下拉列表。如果有,则下拉菜单未初始化,因此不起作用。

不工作的情况:

render() {
    let conditionalComponent:JSX.Element = <></>;
    if (this.state.projectTypeSelected === '1') {
      conditionalComponent = 
      <div className="input-field col s3">
        <MaterializeDropdown options={['1', '2', '3', '4', '5']} placeholderText='number of hits'/>
      </div>;
      //NEED DROPDOWN POST INITIALIZATION HERE
    }
    return(
    //...not relevant JSX elements
    {conditionalComponent}
    )
}

因为条件渲染的事实,下拉列表没有被初始化,因为它在组件挂载时没有被document.querySelectorAll('select')找到。通过// console.log('select count: ', selects.length);检查

所以我尝试在//NEED DROPDOWN POST INITIALIZATION HERE(检查上面的代码)下拉列表中发布初始化:

const element = ReactDOM.findDOMNode(conditionalComponent);

但得到错误:Argument of type 'Element' is not assignable to parameter of type 'ReactInstance | null | undefined'.。有道理,因为似乎没有 react 元素的实例。

所以我尝试创建它:

const element = React.createElement(conditionalComponent);

但得到错误:No overload matches this call. The last overload gave the following error. Argument of type 'Element' is not assignable to parameter of type 'string | FunctionComponent&lt;{}&gt; | ComponentClass&lt;{}, any&gt;'.

我想我需要从 JSX.Element 创建 react 元素实例,这样我就可以找到带有 htmlnode.querySelector('select')html 选择元素来进行初始化,就像在 ComponentDidMount() 中一样。我查看了元素、组件、实例差异documentation,但我无法实现这一点,我不确定这是否是要走的路。从 JSX.Element 创建这个用于初始化想法的实例是否有意义,或者是否有任何其他方法可以解决我的问题?

我试图让我的问题尽可能清晰,但如果有人对这个问题感兴趣,我会根据要求提供一个包含隔离的完整组件的代码框。

【问题讨论】:

    标签: reactjs initialization materialize


    【解决方案1】:

    您的代码中确实存在错误。并反应写了它。 从 render 方法返回值时尝试使用 React 片段。

    render() {
        let conditionalComponent:JSX.Element = <></>;
        if (this.state.projectTypeSelected === '1') {
          conditionalComponent = 
          <div className="input-field col s3">
            <MaterializeDropdown options={['1', '2', '3', '4', '5']} placeholderText='number of hits'/>
          </div>;
          //NEED DROPDOWN POST INITIALIZATION HERE
        }
        return(
          <>
            {conditionalComponent}
          </>
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 2021-05-13
      • 2016-11-27
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      相关资源
      最近更新 更多