在组件之间传递道具

时间:2016-07-19 05:25:22

标签: reactjs

我正在创建一个学习反应的游乐场,并且我已经通过在组件之间传递道具来击中路障。我基本上有两个组件,1是基本组件,然后是另一个组件,它在页面上呈现出一些额外的组件(为简单起见我已将其删除)。我基本上希望能够在其他地方重用这些项目。

我希望能够在示例中呈现组件时指定它是type=submit,如果没有指定默认为type=button

我明显忽略了这一点,因为我收到了错误Cannot read property 'props' of undefined以及下面的代码。任何帮助将不胜感激

按钮组件

import React, {PropTypes} from 'react';
import './button_component.scss';

const propTypes = {
    type: PropTypes.string
}

const ButtonComponent = () => {
  return <button type={this.props.type}>button</button>
}

ButtonComponent.propTypes = propTypes;
export default ButtonComponent;

然后我有一个输出项目的组件

import React from 'react';
import ButtonComponent from './button_component';
import Example from './example'

export default () =>
   <Example>
      <ButtonComponent type='button' />
   </Example>;

1 个答案:

答案 0 :(得分:2)

ButtonComponentfunctional component。因此,您不能在其代码中使用this.props

您应该引入props参数

const ButtonComponent = (props) => {
  return <button type={props.type}>button</button>
}

对象解构和defaultProps可以帮助您简化代码

const ButtonComponent = ({ type }) => {
  return <button type={type}>button</button>
}

ButtonComponent.defaultProps = {
  type: 'button'
}

然后你可以简单地放<ButtonComponent />来渲染一个按钮。