【发布时间】:2017-11-09 05:17:03
【问题描述】:
伙计们,我已经制作了这个创建简单按钮的组件:
class AppButton extends Component {
setOnClick() {
if(!this.props.onClick && typeof this.props.onClick == 'function') {
this.props.onClick=function(){ alert("Hello"); }
}
}
setMessage() {
if(!this.props.message){
this.props.message="Hello"
}
}
render(){
this.setOnClick()
this.setMessage()
return (
<button onClick={this.props.onClick}>{this.props.message}</button>
)
}
}
我还有一个渲染 2 个按钮的组件:
class App extends Component {
render() {
return (
<AppButton onClick={function(){ alert('Test Alert') } } message="My Button" />
<AppButton />
);
}
}
但我收到以下错误:
TypeError:无法定义属性“消息”:对象不可扩展
上面写着:
this.props.message="Hello"
在 AppButton 类的方法 setMessage 中。
编辑 1
我使用npm 生成了react 应用程序,而我package.json 具有以下内容
{
"name": "sample",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"react-scripts": "1.0.7"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
【问题讨论】:
-
旁注 - 我非常喜欢你的提醒和信息。这确实表明您一直在努力使这项工作以您想要的方式工作。我知道那些感觉很好。
-
我只是为了好玩才放它们。一点汗都没有!
-
这样有效吗?两个根节点?
标签: javascript reactjs ecmascript-6