我试图在单击按钮后调用一个函数,到目前为止这是可能的,但我在传递参数时遇到了问题。
这是我的第一个 React 应用程序,请耐心等待。
在这部分调用“clickedQuickreply()”的 onClick 事件将不起作用
它会引发“类型错误:无法读取未定义的属性‘值’”
export function showMessage() {
console.log("Show Message");
let timeStamp = messages.giveTimestamp("not set");
let listItems = messageList.map(d => (
<p className={d.senderId} key={d.senderId}>
{" "}
{d.text}{" "}
</p>
));
let listreply = quickReplyList.map(d => (
<button
className="quickReplyButton"
key={d.id}
value={d.qrText}
**onClick={clickedQuickreply(this.value)}**
>
<span> {d.qrText} </span>
</button>
));
return (
<div>
<div className="timestamp">{timeStamp}</div>
<ul>{listItems}</ul>
<div className="quickreply">{listreply}</div>
</div>
);
}
export function clickedQuickreply(e) {
console.log("Clicked", e);
quickReplyList.length = 0;
//send.sendMessageToServer(query);
}
这是它呈现的代码。将 App.js 命名为“main” 通常我想在每次 fetch 请求完成时重新渲染,但我想我对 React 的理解还不够。
class MessageDisplay extends React.Component {
constructor(props) {
super(props);
this.state = null;
}
componentDidMount() {
window.addEventListener("click", this.tick.bind(this));
window.addEventListener("keypress", this.tick.bind(this));
}
componentWillUnmount() {
window.removeEventListener("click", this.tick.bind(this));
window.removeEventListener("keypress", this.tick.bind(this));
}
componentDidUpdate() {}
tick() {
this.forceUpdate();
}
render() {
setTimeout(() => {
this.forceUpdate();
}, 2000);
return (
<div className="chatBox">
<ui.showMessage />
</div>
);
}
}
那么在那种情况下你如何传递参数呢? 感谢您的时间和耐心等待。
最佳答案
您应该将 onClick={clickedQuickreply(this.value)}
写为 onClick={clickedQuickreply}
。 React 将通过将 event
对象作为内部参数传递给函数来执行该函数。
我在这里注意到的另一件事是,您无需导出函数 clickedQuickreply
,因为它可以像您现在所做的那样通过将其附加到 onClick 来私有(private)用作回调函数
Prop 。所以不用export写,定义在showMessage
函数里面。
关于javascript - react 按钮 onClick 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51929519/