ダイナミックタグ間違ったケーシング

ThaFlaxx:

私は、ボタンでshowModal機能で文字列をもとに反応し、ブートストラップは異なるコンポーネントをレンダリングしようとしていますが、私は取得しています Warning: <MyModal/> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.

このスニペットは、同じ警告をスローしませんが、それは関数内の文字列に基づいて小文字に変換された要素を、作成します。

class Modal extends React.Component {
  render() {
    return (
      <h1>text</h1>
    )
  }
}

class MyButton extends React.Component {
  render() {
    return (
      <button onClick={() => showModal("Modal")}>Show Modal</button>
    )
  }
}

const showModal = (modalName) => {
  const MyModal = modalName
  ReactDOM.render(<MyModal />, document.getElementById("root"));
}

ReactDOM.render(<MyButton />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

あなたはなにか考えはありますか?

ダニエル:

あなたが期限切れしている問題は、追加しようとして反応させることによるものですHTMLのタグ名を<Modal>React.Componentモーダルのではなく。レンダラは、未知のHTMLタグをレンダリングしようとしている反応します。


その他の説明

私は小さなリファクタリングでしたshowModal問題を簡素化する機能を。

const showModal = (modalName) => {
  const MyModal = modalName
  const reactElement = <MyModal />; // equals to React.createElement(MyModal)
  ReactDOM.render(reactElement, document.getElementById("root"));
}

事はということであるreactElementに等しいではありませんModal主な問題は、あなたがReact.component参照を失い、唯一の文字列でそれをレゾールすることができないということです。


Preposeソリューション

そう...あなたは何を行うことができます。

  1. 文字列を使用しません。ただ、値としてReact.Componentを渡します。(雅私は質問のその全体のポイントを知っているが、実際にこのように動作しませんリアクト)。
<button onClick={() => showModal(Modal)}>Show Modal</button>
  1. 使用key value pairsあなたはまだのようReact.Componentを解決するために文字列を使用する場合は、ペアでそれらを格納する必要があります。キーは文字列で、値はReact.Componentです
    const bootstrapComp = {
      modal: Modal,
      ...
    }

    ...

    const showModal = (modalName) => {
      const MyModal = bootstrapComp[modalName]
      ReactDOM.render(reactElement, document.getElementById("root"));
    }

このヘルプを願っています。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=30884&siteId=1