我是 React 新手,正在学习点击事件。但我面临的问题是单击一个按钮我得到“无法获取/[object%20Object]”。这是我使用的代码:
class Engine extends React.Component {
render() {
let types = ["Diesel", "Gazoline"];
return (
<div>
<Car type={types} />
</div>
);
}
}
class Car extends React.Component {
open() {
console.log("You have clicked");
}
render() {
return (
<div>
<h1>
{this.props.type.map((item, index) => {
return <p key={index}>{item}</p>;
})}
</h1>
<button onClick={open}>Remove all</button>
</div>
);
}
}
const box = document.querySelector(".mir");
ReactDOM.render(<Engine />, box);
最佳答案
你需要使用 this.open
,因为它不知道你用 open
指的是什么:
<button onClick={this.open}>Remove all</button>
如果您将函数命名为 foo
而不是 open
,那么它根本无法运行。
您看到该功能的原因是因为它使用默认的 open
命令 built into JavaScript,打开一个新页面。在后台,单击按钮调用 open(e)
,其中 e
是按钮事件。所以它试图打开一个新页面,但它接收的不是 URL,而是一个 object
,因此您会看到收到的错误。
相反,您想使用类中定义的open
。为此,您需要使用 this.open
。
此外,如果你想将一些东西作为参数传递给函数,你需要稍微改变一下。
您可以将 open
更改为:
open = (myparam) => {
console.log("You have clicked");
console.log(myparam);
}
为了bind this
.然后你可以这样做:
<button onClick={_ => this.open("foo")}>Remove all</button>
关于javascript - 在 React 中单击按钮时出现 Cannot GET/[object%20Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57550328/