如何在 React 中访问 Array 内部的对象


const [new, setNew] = useState(
{
"student":
[
{
name:"",
age: ""
}
]
}
);

我如何在数组中设置状态对象我也想将我的输入传递给这个数组,我正在使用反应钩子。

下面是我的手柄更改功能:

const handleChange = (event) => {
//my text editor output
const data = event.target.getContent();
setNew({ ...new.student, summary: data });
console.log(event);
};

const App = () => {
const [objectArray, setObjectArray] = React.useState({
students: [
{
name: "",
age: ""
},
{
name: "",
age: ""
},
{
name: "",
age: ""
}
]
});
const handleChange = (index, name, value) => {
console.log("changed - ", index, name, value);
const updated = {...objectArray};
updated.students[index][name] = value;
setObjectArray(updated);
};
return (
<div className="container">
<div className="row row-cols-2">
<div className="col">
{objectArray.students.map((s, i) => (
<div className="form-group">
<div className="input-group mb-3">
<div className="input-group-prepend">
<span className="input-group-text" id="basic">
Name
</span>
</div>
<input
type="text"
className="form-control"
value={s.name}
onChange={e => handleChange(i, "name", e.target.value)}
placeholder="Name"
aria-label="Name"
aria-describedby="basic"
/>
</div>
<div className="input-group mb-3">
<div className="input-group-prepend">
<span className="input-group-text" id="basic">
Age
</span>
</div>
<input
type="text"
className="form-control"
value={s.age}
onChange={e => handleChange(i, "age", e.target.value)}
placeholder="Age"
aria-label="Age"
aria-describedby="basic"
/>
</div>
</div>
))}
</div>
<div className="col">{JSON.stringify(objectArray, null, 2)}</div>
</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0-alpha.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0-alpha.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

setNew({student: [ ...new.student, {summary: data }]});

你想像这样做SMT吗?

相关内容

  • 没有找到相关文章

最新更新