React.js:将默认值设置为prop [英] React.js: Set a Default value into a prop

查看:33
本文介绍了React.js:将默认值设置为prop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

研究员,我制作了这个组件,它创建了一个简单的Button:

Fellows I have made this Component that creates a simple Button:

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个按钮的Component:

And I have an another Component that renders 2 Buttons:

class App extends Component {
  render() {
    return (
          <AppButton onClick={function(){ alert('Test Alert') } } message="My Button" />
          <AppButton />
    );
  }
}

但是出现以下错误:

TypeError:无法定义属性"message":对象不可扩展

TypeError: can't define property "message": Object is not extensible

在显示以下内容的行上:

On the line that says:

        this.props.message="Hello"

AppButton 类的方法 setMessage 中.

我使用 npm 生成了react应用程序,而我 package.json 具有以下内容

I generated the react application using npm and me package.json has the following content

{
  "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 应该可以满足您的需求:

I believe that defaultProps should do what you need:

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.

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 .

Edit for clarity: There should be no need for you setMessage in this instance.

这篇关于React.js:将默认值设置为prop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆