簡體   English   中英

在變量中聲明表單時反應錯誤

[英]React error when form declared in a variable

我正在做一個反應。 我剛剛創建了這個名為 Input.jsx 的組件

import React from "react";

const Input = (label, placeholder) => {
  return (
    <label htmlFor={label}>
      {label}
      <input type="text" placeholder={placeholder} />
    </label>
  );
};

export default Input;

我導入它並在 index.js 中使用它

import React from "react";
import ReactDOM from "react-dom";
import input from "./components/Input.jsx";

const App = () => {
  const InputDrop = input("label", "placeholder");
  return (
    <div>
      <InputDrop />
    </div>
  );
};

export default App;

ReactDOM.render(<App />, document.getElementById("root"));

這不起作用,我在控制台中收到此錯誤

但是,如果我在沒有在 var 中聲明表單的情況下執行此操作,則它可以工作,如下所示:

import React from "react";
import ReactDOM from "react-dom";
import input from "./components/Input.jsx";

const App = () => {
  return <div>{input("label", "placeholder")}</div>;
};

export default App;

ReactDOM.render(<App />, document.getElementById("root"));

我不知道為什么不起作用。 感謝所有類型的幫助或建議

永遠不應該調用函數之類的組件 通過React.createElement()方法在內部為你做這件事,因為 babel 在編譯期間為你轉譯它。

  1. React 函數組件接受props作為它們的第一個參數,它是傳遞給組件的屬性的對象。 使用 ES6 析構語法:

     // note the curly braces { } for destructuring const InputDrop = ({ label, placeholder }) => ( <label htmlFor={label}> {label} <input type="text" placeholder={placeholder} /> </label> )
  2. 您應該傳遞 props 而不是直接將組件作為函數調用

    <InputDrop label="label" placeholder="placeholder" />

但總的來說,聽起來沒有居高臨下的意思,聽起來你應該徹底閱讀react 文檔,至少是最基本的。 幸運的是,它是目前最好的文檔之一,因此很容易閱讀和學習。

您應該將它直接用作組件

import Input from "./components/Input.jsx";

const App = () => {
  return (
    <div>
      <Input label="label" placeholder="placeholder"/>
    </div>
  );
};

但您必須將其簽名更改為const Input = ({label, placeholder}) => {


或者如果作為函數使用,直接渲染變量

const App = () => {
  const InputDrop = input("label", "placeholder");
  return (
    <div>
      {InputDrop}
    </div>
  );
};

雖然對於這種情況,使用這種方法沒有多大意義。

試試下面的方法

輸入組件

import React from "react";

const Input = ({label, placeholder}) => 
      <label htmlFor={label}>
      {label}
      <input type="text" placeholder={placeholder} />
    </label>

export default Input;

索引.js

import React from "react";
import ReactDOM from "react-dom";
import input from "./components/Input.jsx";

const App = () => 
    <div>
      <Input label="label" placeholder="placeholder" />
    </div>

export default App;

ReactDOM.render(<App />, document.getElementById("root"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM