本文介绍了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 />
    );
  }
}

但是出现以下错误:

在显示以下内容的行上:

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

推荐答案

相信应该可以满足您的需求:

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

从文档中

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

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

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

05-27 19:49
查看更多