gpt4 book ai didi

javascript - React.js : Set a Default value into a prop

转载 作者:行者123 更新时间:2023-12-03 12:58:15 24 4
gpt4 key购买 nike

我已经制作了这个组件来创建一个简单的按钮:

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: can't define property "message": Object is not extensible

线上写着:

        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"
}
}

最佳答案

我相信defaultProps应该做你需要的事情:

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"); }
};

来自文档:

The defaultProps will be used to ensure that this.props.name will have a value if it was not specified by the parent component. The propTypes typechecking happens after defaultProps are resolved, so typechecking will also apply to the defaultProps.

为清楚起见进行编辑:在这种情况下,您应该不需要setMessage

关于javascript - React.js : Set a Default value into a prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44419650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com