如何从事件处理程序内的对象中打印多个键?
这是我代码的链接-https://codesandbox.io/s/suspicious-hamilton-erkqv
在第35行上,我将其称为" x"对象的事件处理程序更改名称。我能够打印一个称为"名称"的密钥(x.Name(如何打印X对象的所有3个道具(名称,ID,类型(??
尝试将x转换为带有object.keys(x(的数组
const ChangeName = x => {
setvalue(x.name);
};
<div>{value}</div> // display the results
您的值不是一个数组,它是为什么不能使用地图方法的对象,这就是它的工作方式:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function App() {
const [posts, setposts] = useState([]);
const [value, setvalue] = useState("");
useEffect(() => {
const posts = [
{
id: 1,
name: "Name 1",
type: "Type 1"
},
{
id: 2,
name: "Name 2",
type: "Type 2"
},
{
id: 3,
name: "Name 3",
type: "Type 3"
},
{
id: 4,
name: "Name 4",
type: "Type 4"
}
];
setposts(posts);
}, []);
const ChangeName = x => {
setvalue(x);
};
return (
<div>
<ul>
{posts.map(post => (
<li key={post.id}>
{post.name},{post.type}
<button onClick={() => ChangeName(post)}>More Info</button>
</li>
))}
</ul>
<div>
{value.name}
{value.id}
{value.type}
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
运行代码:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function App() {
const [posts, setposts] = useState([]);
const [values, setvalue] = useState([]);
useEffect(() => {
const posts = [
{
id: 1,
name: "Name 1",
type: "Type 1"
},
{
id: 2,
name: "Name 2",
type: "Type 2"
},
{
id: 3,
name: "Name 3",
type: "Type 3"
},
{
id: 4,
name: "Name 4",
type: "Type 4"
}
];
setposts(posts);
}, []);
const ChangeName = x => {
console.log(Object.values(x));
Object.values(x).map(k => setvalue(k));
};
return (
<div>
<ul>
{posts.map(post => (
<li key={post.id}>
{post.name},{post.type}
<button onClick={ChangeName.bind(this, post)}>More Info</button>
</li>
))}
</ul>
<div>{values}</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
您需要设置值而不是值。