我想使用 React 创建一个网络应用程序编码游戏,其中涉及评估一些用户(javascript)输入。
constructor(props) {
super(props);
this.state = {
code: ''
};
}
handleChange(key) {
return event => this.setState({ [key]: event.target.value });
}
funScript() {
eval(this.state.code);
}
anotherScript() {
console.log("Will this work?");
}
render() {
return (
<div>
<input
type={"text"}
value={this.state.code}
onChange={this.handleChange('code')}
/>
<button onClick={this.funScript()} >run</button>
</div>
);
}
我希望文本输入能够在用户按下按钮时评估 JavaScript(用户在 this.anotherScript() 中键入;并且控制台记录“这有效吗?”。不幸的是,它不能工作,我怀疑这是 React 特有的问题。一旦输入框被输入,它就会尝试计算字符串(甚至没有按下按钮!)。请参阅此处的示例:https://codesandbox.io/s/54rkp584ll
有人有一个合适的 React 解决方案,不会在第一个字符输入时破坏 JavaScript(并评估函数)吗?
最佳答案
当你输入时
<button onClick={this.funScript()} >run</button>
您正在调用this.funScript
。删除括号,您就可以像您想要的那样传递函数。另外,funScript
需要绑定(bind)到它才能工作。
关于javascript - 在 react 中按下按钮时评估输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47640483/