将一段数据从子组件传递到父组件是否是反应中的反模式?

考虑以下示例...


我有一个名为 ChemVisualisation.jsx 的组件,如下所示


const ChemVisualization = props => {


 const { getChemists, chemists } = props;


 useEffect(() => {

    getChemists();

  }, [getChemists]);


// useState hook is used here 

// handleChange sets the name property

// i check for chemists based on name property here and pass it as props to 

// SearchableDropdown component where it renders the list 


 const getChemistId = id => {

    console.log(id);

    // showing undefined

  };


return(

 <SearchableDropdown

            getName={ChemistAnalytics}

            onChange={e => handleChange(e)}

            name="name"

            value={name}

            onSubmit={e => handleSubmit(e)}

            entities={result}

            handleClick={getChemistId}

          />

);

}

SearchableDropdown.jsx


const SearchableDropdown = props => {


// destructure props here

return(

<div className="control has-icons-left w-3/5 ">

        <input

          type="text"

          placeholder="search"

          value={value}

          name={name}

          onChange={onChange}

          className="input"

          autoComplete="off"

        />

        <span className="icon is-left">

          <FontAwesomeIcon icon={faSearch}></FontAwesomeIcon>

        </span>

      </div>

      {entities && (

        <div className="dropdown">

          <div className="dropdown-content">

            {entities.map(r => (

              <div

                className="dropdown-item text-xl hover:bg-gray-400 w-full"

                key={r._id}

                onClick={r => handleClick(r._id)}

              >

                {r.chem_name}

              </div>

            ))}

          </div>

        </div>

      )}

);

}

当我单击下拉项时,我没有在其父组件中获取 id。


我的问题是如何获取我点击的下拉项目的 id?将数据从子组件传递到其父组件是一种反模式吗?


交互式爱情
浏览 117回答 2
2回答

翻阅古今

子组件调用其父组件为响应事件而提供给它们的函数是正常的。然后,父级将根据需要使用新信息重新呈现。这使状态信息保持相当“高”。更多内容在文档中的Lifting State Up中。在你的例子中<div className="dropdown-content">&nbsp; {entities.map(r => (&nbsp; &nbsp; <div&nbsp; &nbsp; &nbsp; className="dropdown-item text-xl hover:bg-gray-400 w-full"&nbsp; &nbsp; &nbsp; key={r._id}&nbsp; &nbsp; &nbsp; onClick={r => handleClick(r._id)}&nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; {r.chem_name}&nbsp; &nbsp; </div>&nbsp; ))}</div>问题是你正在用不同的(回调的参数)遮蔽r(回调的参数)。调用点击处理程序的第一个参数是一个事件对象。如果您不想要它,请不要接受该参数:mapronClick<div className="dropdown-content">&nbsp; {entities.map(r => (&nbsp; &nbsp; <div&nbsp; &nbsp; &nbsp; className="dropdown-item text-xl hover:bg-gray-400 w-full"&nbsp; &nbsp; &nbsp; key={r._id}&nbsp; &nbsp; &nbsp; onClick={() => handleClick(r._id)}&nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; {r.chem_name}&nbsp; &nbsp; </div>&nbsp; ))}</div>唯一的变化是用rin()替换onClick={() => handleClick(r._id)}。

绝地无双

onClick={e&nbsp;=>&nbsp;handleClick(r._id)}使用 e 而不是 r。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript