使用受控状态更新反应形式

时间:2019-09-29 12:58:10

标签: javascript reactjs ecmascript-6

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

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属性?

3 个答案:

答案 0 :(得分:1)

我建议,从数据中建立一个状态,然后使其成为受控组件。尝试以下类似的方法

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
);

答案 1 :(得分:0)

这是通过f_name和l_name ..添加名称attr的简单方法。

https://codesandbox.io/embed/flamboyant-cherry-tvq7s

enter image description here

答案 2 :(得分:0)

根据我的选择,我将使用正则表达式:

import React from "react";
import ReactDOM from "react-dom";

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 => {
        for(let key of Object.keys(o)) {
          let name = /([a-zA-Z]+_name)/g.test(key) ? o[key] : ''
          return <input name={name} onChange={handleChange} type="text"/>
        }
      })}
    </div>
  );
}

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