繁体   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