我必须读取一个端点并将值绑定到表单上,但是我正在努力将数组的值绑定到标签中
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_name
和l_name
属性绑定到name
属性?
答案 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)
答案 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);