Javascript React.js:将默认值设置为道具
我制作了这个组件,创建了一个简单的按钮:Javascript React.js:将默认值设置为道具,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我制作了这个组件,创建了一个简单的按钮: class AppButton extends Component { setOnClick() { if(!this.props.onClick && typeof this.props.onClick == 'function') { this.props.onClick=function(){ alert("Hello"); } } } setMessage() { if(!thi
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>
)
}
}
在AppButton
类的方法setMessage
中
编辑1
我使用npm
和mepackage生成了react应用程序
{
"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"
}
}
您是否使用React v.14或更高版本?道具对象现在已冻结,无法更改。您可以改用React.cloneElement您不能设置道具,必须改用state
如果需要更改该值,则应将其存储在状态中,因为道具是静态的
你应该这样做:
this.setState({message: 'your message'});
在渲染方法中,将其用作:
{this.state.message}
作为建议,还应在构造函数中使用该值初始化状态:
constructor(props){
super(props);
this.state = {
message: ''
}
}
setOnClick
你会找到一个很好的解释。我认为这应该满足你的需要:
import PropTypes from 'prop-types';
class AppButton extends Component {
render(){
return (
<button onClick={this.props.onClick}>{this.props.message}</button>
)
}
};
AppButton.propTypes = {
message: PropTypes.string,
onClick: PropTypes.func
};
AppButton.defaultProps = {
message: 'Hello',
onClick: function(){ alert("Hello"); }
};
从“道具类型”导入道具类型;
类AppButton扩展组件{
render(){
返回(
{this.props.message}
)
}
};
AppButton.propTypes={
消息:PropTypes.string,
onClick:PropTypes.func
};
AppButton.defaultProps={
留言:“你好”,
onClick:function(){alert(“Hello”);}
};
从文档中:
defaultProps将用于确保this.props.name在未由父组件指定时具有值。propTypes类型检查发生在defaultProps解析之后,因此类型检查也将应用于defaultProps
为清晰起见进行编辑:在这种情况下,您不需要设置消息。返回(
return (
<button onClick={this.props.onClick}>{this.props.message || "Default text"}</button>
);
{this.props.message | |“默认文本”}
);
这将检查prop的值,如果未定义或为空,则默认消息将替换prop 旁注-我绝对喜欢你的提醒和信息。这真的表明你一直在努力让它按你想要的方式工作。我知道这些感觉很好。我只是为了好玩才放的。不用担心!这是真的吗?这两个根节点?有时我会使用ES6 destructuring{names=[]}
@Pedrammarandi-yep分配默认值,如果您创建的功能组件不需要生命周期挂钩,这也是一个很好的方法。我认为v.14及以上版本的完整示例会更有益
import PropTypes from 'prop-types';
class AppButton extends Component {
render(){
return (
<button onClick={this.props.onClick}>{this.props.message}</button>
)
}
};
AppButton.propTypes = {
message: PropTypes.string,
onClick: PropTypes.func
};
AppButton.defaultProps = {
message: 'Hello',
onClick: function(){ alert("Hello"); }
};
return (
<button onClick={this.props.onClick}>{this.props.message || "Default text"}</button>
);