クラス名をReactコンポーネントに渡す 質問する

クラス名をReactコンポーネントに渡す 質問する

スタイルを変更するために、React コンポーネントにクラス名を渡そうとしていますが、うまく動作しないようです。

class Pill extends React.Component {

  render() {

    return (
      <button className="pill {this.props.styleName}">{this.props.children}</button>
    );
  }

}

<Pill styleName="skill">Business</Pill>

それぞれのスタイルを持つクラスの名前を渡して、ピルのスタイルを変更しようとしています。私はReactの初心者なので、正しいやり方ではないかもしれません。ありがとうございます

ベストアンサー1

React では、解釈された式を渡すときは、中括弧のペアを開く必要があります。次を試してください:

render () {
  return (
    <button className={`pill ${ this.props.styleName }`}>
      {this.props.children}
    </button>
  );
}

使用方法クラス名npm パッケージ

import classnames from 'classnames';

render() {
  return (
    <button className={classnames('pill', this.props.styleName)}>
      {this.props.children}
    </button>
  );
}

おすすめ記事