【发布时间】: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<{}> | ComponentClass<{}, any>'.
我想我需要从 JSX.Element 创建 react 元素实例,这样我就可以找到带有 htmlnode.querySelector('select') 的 html 选择元素来进行初始化,就像在 ComponentDidMount() 中一样。我查看了元素、组件、实例差异documentation,但我无法实现这一点,我不确定这是否是要走的路。从 JSX.Element 创建这个用于初始化想法的实例是否有意义,或者是否有任何其他方法可以解决我的问题?
我试图让我的问题尽可能清晰,但如果有人对这个问题感兴趣,我会根据要求提供一个包含隔离的完整组件的代码框。
【问题讨论】:
标签: reactjs initialization materialize