2016-07-19 26 views
3

私は反応を学ぶために少し遊び場を作りました。コンポーネント間に小道具を渡して道路ブロックを打ちました。私は本質的に2つのコンポーネントを持っています.1つはベースコンポーネントで、もう1つはいくつかのエクストラ(これは単純化のために削除しました)を使ってページ上にレンダリングしています。私は本質的に、他の場所でアイテムを再利用できるようにしたい。コンポーネント間に小道具を渡す

例でコンポーネントをレンダリングするときに、type=submitが指定されていない場合はtype=submitと指定してください。デフォルトはtype=buttonです。

以下のコードでエラーCannot read property 'props' of undefinedが表示されるので、私は明らかにこの点を紛失しています。すべてのヘルプは

Buttonコンポーネント

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

ButtonComponentfunctional componentで出力コンポーネントを持っています。したがって、コードにthis.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' 
} 

を作るのを助けることができprops引数を導入すべきである、あなたは、単にボタンをレンダリングするために<ButtonComponent />を置くことができます。

+0

これはまさに私の問題でした。ありがとうございました。また、実際に役立った機能的なコンポーネントを説明するリンクにも感謝します! – Ash

+0

@Ashコードに誤字があることに注意してください。 'type:propTypes.string'は' type:PropTypes.string'でなければなりません。 – Alik

関連する問題