React.js:将默认值设置为道具

时间:2017-06-07 17:54:32

标签: 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(!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:无法定义属性“message”:对象不可扩展

在线上说:

        this.props.message="Hello"

setMessage类的方法AppButton中。

编辑1

我使用npm生成了反应应用程序,而我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"
  }
}

4 个答案:

答案 0 :(得分:54)

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

来自文档:

  

defaultProps将用于确保this.props.name具有一个值(如果父组件未指定)。 propTypes类型检查在defaultProps解析后发生,因此类型检查也将应用于defaultProps。

为了清晰起见而修改:在这种情况下,您不需要setMessage

答案 1 :(得分:6)

return (
      <button onClick={this.props.onClick}>{this.props.message || "Default text"}</button>
);

这将检查prop的值,如果它未定义或为null,则默认消息将替换prop。

答案 2 :(得分:0)

您使用的是React v.14或更高版本吗?道具对象现在已冻结,无法更改。您可以使用React.cloneElement

答案 3 :(得分:0)

你不能设置道具,你必须改用状态。

如果需要更改值,则应将其存储在状态中,因为道具是静态的。

你应该这样做:

this.setState({message: 'your message'});

在render方法中使用它:

{this.state.message}

作为推荐,您还应该在构造函数中使用该值初始化状态:

constructor(props){
  super(props);

  this.state = {
    message: ''
  }
}

同样会发生在setOnClick

您会发现here对此有一个很好的解释。

相关问题