LoginSignup
2
1

More than 5 years have passed since last update.

React の SFC に default props を与える方法と実用例

Posted at

SFC.defaultProps = {渡したいprops} でOK。

default_props.js

const AnySFC = (props) => (
   <div>{props.defaultMessage}</div>
)

AnySFC.defaultProps = {
  defaultMessage: 'デフォルトメッセージ',
};

デフォルトで何か style を当てつつ、style を変更したいときは props から変更できるようにする例。
style のプロパティをスプレッドシンタックスでマージしてます。

default_styled_sfc.jsx
import React from 'react';

const defaultProps = {
    style: { color: 'red' },
};

const DefaultStyledSFC = (props) => (
    <div {...props} style={{ ...defaultProps.style, ...props.style }}>
        {props.children}
    </div>
);
DefaultStyledSFC.defaultProps = defaultProps;

export default DefaultStyledSFC;

<DefaultStyledSFC style={{ color: 'green' }}> などで上書き可能。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1