Javascript 按按钮输出的名称
我有一个div,按下按钮可以显示名称。在下面的两个按钮中,如果单击第一个按钮,则会显示John的名字,如果单击第二个按钮,则会显示Donald。错在哪里Javascript 按按钮输出的名称,javascript,reactjs,Javascript,Reactjs,我有一个div,按下按钮可以显示名称。在下面的两个按钮中,如果单击第一个按钮,则会显示John的名字,如果单击第二个按钮,则会显示Donald。错在哪里 import React, { Component } from 'react'; class trueName extends Component { constructor(props) { this.state = { name: {}, }; } john = ()=>{ co
import React, { Component } from 'react';
class trueName extends Component {
constructor(props) {
this.state = {
name: {},
};
}
john = ()=>{
const {name}= this.state;
this.setState({name:"John"})
}
donald = ()=>{
const {name}= this.state;
this.setState({name:"Donald"})
}
render() {
return(
<div >
<div className="SelectName">
<span>{this.name}</span>
</div>
<button
className = "one"
onClick={ this.john}>
<span>My name John</span>
</button>
<button
className = "two"
onClick={ this.donald}
>
<span>My name Donald</span>
</button>
</div>
)
}
}
export default trueName;
import React,{Component}来自'React';
类trueName扩展组件{
建造师(道具){
此.state={
姓名:{},
};
}
约翰=()=>{
const{name}=this.state;
this.setState({name:“John”})
}
唐纳德=()=>{
const{name}=this.state;
this.setState({name:“Donald”})
}
render(){
返回(
{this.name}
我叫约翰
我叫唐纳德
)
}
}
导出默认trueName;
您需要使用'
、“
或```将name的值设置为字符串:
this.setState({name:'John'})
/// ...
this.setState({name:'Donald'})
此外,只有构造函数的开头应使用大写字母,而不是方法,请将函数
John
重命名为John
您需要使用'
,“
或``来将name的值设置为字符串:
this.setState({name:'John'})
/// ...
this.setState({name:'Donald'})
此外,只有构造函数的开头应该使用大写字母,而不是方法,请将函数
John
重命名为John
,正如其他人提到的,您需要将值设置为字符串
但是,当您显示值时,也会出现错误。您正在查找
this.name
,而要显示的是this.state.name
正如其他人所提到的,您需要将值设置为字符串
但是,当您显示值时,也会出现错误。您正在查找
this.name
,而要显示的是this.state.name此处缺少引号:this.setState({name:{John})
此处缺少引号:this.setState({name:{John})