我必须读取一个端点并将值绑定到表单上,但是我正在努力将数组的值绑定到标签中

function App() {
  const data = [
    {
      f_name: "alicia"
    },
    {
      l_name: "johnson"
    }
  ];

  function handleChange(e) {
    console.log("e", e.target.value);
  }

  return (
    <div className="App">
      {data.map(o => (
        <input name={o} onChange={handleChange} type="text" />
      ))}
    </div>
  );
}


https://codesandbox.io/s/cocky-ives-cx5nx

如何将f_namel_name属性绑定到name attr?

最佳答案

我建议,根据数据构建状态,然后将其设为受控组件。尝试如下



import React, {useState} from "react";
import ReactDOM from "react-dom";

function App() {
  const data = [
    {
      f_name: "alicia"
    },
    {
      l_name: "johnson"
    }
  ];

  const [state, setState] =  useState(data.reduce((acc, val) => {
    acc = {...acc, ...val}
    return acc;
  }, {}));
  console.log(state);

  function handleChange(e, key) {
    setState({...state, [key]: e.target.value });
  }

  return (
    <div className="App">
      {Object.keys(state).map((key) => (
        <input
        key={key}
        name={key}
        value={state[key]}
        onChange={(e) => {
            handleChange(e,key);
          }
        }
          type="text"
        />
      ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App />, rootElement
);

10-07 14:48