【问题标题】:how to create a function which has a function as one of its arguments react如何创建一个函数,该函数具有一个函数作为其参数之一反应
【发布时间】:2020-08-03 03:20:53
【问题描述】:

我正在尝试创建一个函数,该函数将函数(在本例中为 react hook useState 函数)作为其参数之一,以简化下面的代码(我只显示了我的实际数据大约有 2 列30 列,因此我尝试简化)

const [teamName, setTeamName] = useState('')
const [teamLocation, setTeamLocation] = useState('')

    <div classname="editHere">
    <input value={teamName} onChange={(e) => {  setTeamName(e.target.value) }}/>
    </div>

    <div className="editHere">
    <input value={teamLocation} onChange={(e) => {  setTeamLocation(e.target.value) }}/>
    </div>

我正在尝试使用以下函数来做到这一点

function dropDownRow(value, setValue()) {
        return (
            <div className="editHere">
            <input value={value} onChange={(e) => {  setValue(e.target.value) }}/>
            </div>
        )

    }

然后返回我想输入的第一个 sn-p 中显示的内容

{dropDownRow(teamName, setTeamName())}
{dropDownRow(teamLocation, setTeamLocation())}

显然这不起作用所以有人对我如何做我想要实现的目标有任何建议吗?

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    像这样创建你的函数...

    function DropDownRow({ value, setValue }) {
      return (
        <div className="editHere">
          <input value={value} onChange={e => setValue(e.target.value)} />
        </div>
      );
    }
    
    

    你的参考应该喜欢...

          <DropDownRow value={teamName} setValue={setTeamName} />
          <DropDownRow value={teamLocation} setValue={setTeamLocation} />
    

    Example Here ...

    【讨论】:

      【解决方案2】:

      去掉括号:

      function dropDownRow(value, setValue) {
      

      这里:

      {dropDownRow(teamName, setTeamName)}
      {dropDownRow(teamLocation, setTeamLocation)}
      

      或者你也可以使用更简洁的语法:

      const DropDownRow = ({ value, setValue }) => ...
      

      然后

      <DropDownRow value={teamName} setValue={setTeamName} />
      <DropDownRow value={teamLocation} setValue={setTeamLocation} />
      

      【讨论】:

        猜你喜欢
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 2019-04-28
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多