onChange 属性值未定义

E.Y*_*RIM 1 javascript reactjs primereact react-props

我正在使用reactprime TreeSelect。我想通过编辑名为 的变量来创建一个数组returnArray,并通过 props 将其发送到主组件的状态。但onChange似乎未定义。相同的过程正在工作OnValueChanged

主要组成部分:

return(
          <SubComponent>
            onChange={(val) => {
              console.log("here")
            if (val)
              setFormDataDetails({
                ...formDataDetails,
                [item.NS_CI_ID]: val,
              });
          }}
          </SubComponent>
);
Run Code Online (Sandbox Code Playgroud)

子组件:

  const nodeStateCh = (e) => {
    setSelectedNodeKeys(e.value)
    let rArray= []
    rArray.push("test")
    if (props.onChange) {  //undefined...
      props.onChange(returnArray)
    }
    
  }



  return (
    <div className="card flex justify-content-center">
      <TreeSelect
        value={selectedNodeKeys}
        onChange={nodeStateCh}
        options={nodes}
        metaKeySelection={false}
        filter
        className="md:w-20rem w-full"
        selectionMode="checkbox"
        display="chip"
        placeholder="Select Items"
      >
        {' '}
      </TreeSelect>
    </div>
  )
Run Code Online (Sandbox Code Playgroud)

小智 6

您将 onChange 作为子项传递,而不是作为参数传递,这就是 porpos 为空的原因。

而不是这个:

 <SubComponent>
     onChange={(val) => {
         console.log("here")
         if (val)
           setFormDataDetails({
                ...formDataDetails,
                [item.NS_CI_ID]: val,
           });
     }}
 </SubComponent>
Run Code Online (Sandbox Code Playgroud)

应该是这样的:

 <SubComponent
     onChange={(val) => {
         console.log("here")
         if (val)
           setFormDataDetails({
                ...formDataDetails,
                [item.NS_CI_ID]: val,
           });
     }}
 />
Run Code Online (Sandbox Code Playgroud)

然后,您将此函数作为名为 onChange 的参数传递。

在您的方法中,您也将其作为参数传递,但特殊参数称为“children”,但它用于不同的目的。

您可以在文档中阅读更多相关信息: https://react.dev/learn/passing-props-to-a-component#passing-jsx-as-children