React组件 – 传递数值

huangapple go评论69阅读模式
英文:

React Components - Passing values

问题

Sure, here are the translations of the code-related parts:

  1. 如何在用户在输入框内输入值并点击按钮后,从 LoginPanel 组件中使用 name 值,并在 App 组件中使用它。
  2. 如何首先渲染 LoginPanel,如果输入了名字并点击了按钮,如何切换到 App 组件的视图?

你的代码看起来像这样:

import React, { useState } from "react";

function LoginPanel() {
  const [fname, setName] = useState({
    fName: "",
    password: "",
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setName(prevValue => {
      return {
        ...prevValue,
        [name]: value
      };
    });
  }

  return (
    <div className="container">
      <h1>
        Log In 
      </h1>
      <form>
        <input
          onChange={handleChange}
          name="fName"
          value={fname.fName}
          placeholder="First Name"
        />
        <input
          type='password'
          name="password"
          placeholder="Password"
        />
        <button>Submit</button>
      </form>
    </div>
  );
}

export default LoginPanel;
import React, { useState } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";

function App() {
  const [notes, setNotes] = useState([]);

  function addNote(newNote) {
    setNotes(prevNotes => {
      return [...prevNotes, newNote];
    });
  }

  function deleteNote(id) {
    setNotes(prevNotes => {
      return prevNotes.filter((noteItem, index) => {
        return index !== id;
      });
    });
  }

  return (
    <div>
      <Header />
      <CreateArea onAdd={addNote} />
      {notes.map((noteItem, index) => {
        return (
          <Note
            key={index}
            id={index}
            title={noteItem.title}
            content={noteItem.content}
            onDelete={deleteNote}
          />
        );
      })}
      <Footer />
    </div>
  );
}

export default App;
import React, { useState } from "react";
import App from "./App";
import LoginPanel from "./LoginPanel";

function Main() {
  const [isLogged, setLogged] = useState(false);

  return (
    <div>
      {!isLogged ? <LoginPanel /> : <App />}
    </div>
  )
}

export default Main

请注意,这是您提供的代码的翻译,您可以根据需要进一步使用这些翻译。如果您有其他问题或需要进一步的帮助,请告诉我。

英文:

I need some help:

  1. How to use value name from LoginPanel component after user write it inside the input and click button and use it inside the App component.
  2. How to render LoginPanel as first and if input name is written and button is clicked switch view to the App component?

I can't understand that.

My code looks like that.

import React, { useState } from &quot;react&quot;;

function LoginPanel() {
  const [fname, setName] = useState({
    fName: &quot;&quot;,
    password: &quot;&quot;,
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setName(prevValue =&gt; {
      return {
        ...prevValue,
        [name]: value
      };
    });
  }

  return (
    &lt;div className=&quot;container&quot;&gt;
      &lt;h1&gt;
        Log In 
      &lt;/h1&gt;
      &lt;form&gt;
        &lt;input
          onChange={handleChange}
          name=&quot;fName&quot;
          value={fname.fName}
          placeholder=&quot;First Name&quot;
        /&gt;
        &lt;input
          type=&#39;password&#39;
          name=&quot;password&quot;
          placeholder=&quot;Password&quot;
        /&gt;
        &lt;button&gt;Submit&lt;/button&gt;
      &lt;/form&gt;
    &lt;/div&gt;
  );
}

export default LoginPanel;
import React, { useState } from &quot;react&quot;;
import Header from &quot;./Header&quot;;
import Footer from &quot;./Footer&quot;;
import Note from &quot;./Note&quot;;
import CreateArea from &quot;./CreateArea&quot;;

function App() {
  const [notes, setNotes] = useState([]);

  function addNote(newNote) {
    setNotes((prevNotes) =&gt; {
      return [...prevNotes, newNote];
    });
  }

  function deleteNote(id) {
    setNotes((prevNotes) =&gt; {
      return prevNotes.filter((noteItem, index) =&gt; {
        return index !== id;
      });
    });
  }

  return (
    &lt;div&gt;
      &lt;Header /&gt;
      &lt;CreateArea onAdd={addNote} /&gt;
      {notes.map((noteItem, index) =&gt; {
        return (
          &lt;Note
            key={index}
            id={index}
            title={noteItem.title}
            content={noteItem.content}
            onDelete={deleteNote}
          /&gt;
        );
      })}
      &lt;Footer /&gt;
    &lt;/div&gt;
  );
}

export default App;
import React, { useState } from &quot;react&quot;;
import App from &quot;./App&quot;;
import LoginPanel from &quot;./LoginPanel&quot;;

function Main() {
  const [isLogged, setLogged] = useState(false);

  return (
    &lt;div&gt;
      {!isLogged ? &lt;LoginPanel /&gt; : &lt;App /&gt;}
    &lt;/div&gt;
  )
}

export default Main

I tried a lot of react tutorials and documentation.
I want use value name from LoginPanel component after user write it inside the input and click button and use it inside the App component and to render LoginPanel as first and if input name is written and button is clicked switch view to the App component?

答案1

得分: 1

提升 "name" 状态到父组件 Main,并将状态和状态更新函数作为 props 传递给组件。当表单提交时,更新状态。

更多详细信息请查看在组件之间共享状态

示例:

function Main() {
  const [loggedName, setLoggedName] = useState("");
  return (
    <div>
      {!name ? <LoginPanel setName={setLoggedName} /> : <App name={loggedName} />}
    </div>
  )
}
function LoginPanel({ setLoggedName }) {
  const [fname, setName] = useState({
    fName: "",
    password: "",
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setName(prevValue => {
      return {
        ...prevValue,
        [name]: value
      };
    });
  }

  function login(event) {
    event.preventDefault();
    setLoggedName(fname); // <-- 更新父组件状态
  }

  return (
    <div className="container">
      <h1>
        Log In 
      </h1>
      <form onSubmit={login}> // <-- 表单提交处理程序
        <input
          onChange={handleChange}
          name="fName"
          value={fname.fName}
          placeholder="First Name"
        />
        <input
          type='password'
          name="password"
          placeholder="Password"
        />
        <button>Submit</button>
      </form>
    </div>
  );
}

export default LoginPanel;
function App({ loggedName }) {
  ... 使用传递的 loggedName prop 进行需要的操作 ...

  ...
}

export default App;
英文:

Lift the "name" state up to the parent, Main, and pass the state and state updater function down as props to the components. When the form is submitted, update the state.

For more details see Sharing State Between Components.

Example:

function Main() {
  const [loggedName, setLoggedName] = useState(&quot;&quot;);
  return (
    &lt;div&gt;
      {!name ? &lt;LoginPanel setName={setLoggedName} /&gt; : &lt;App name={loggedName} /&gt;}
    &lt;/div&gt;
  )
}
function LoginPanel({ setLoggedName }) {
  const [fname, setName] = useState({
    fName: &quot;&quot;,
    password: &quot;&quot;,
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setName(prevValue =&gt; {
      return {
        ...prevValue,
        [name]: value
      };
    });
  }

  function login(event) {
    event.preventDefault();
    setLoggedName(fname); // &lt;-- update parent state
  }

  return (
    &lt;div className=&quot;container&quot;&gt;
      &lt;h1&gt;
        Log In 
      &lt;/h1&gt;
      &lt;form onSubmit={login}&gt; // &lt;-- form submit handler
        &lt;input
          onChange={handleChange}
          name=&quot;fName&quot;
          value={fname.fName}
          placeholder=&quot;First Name&quot;
        /&gt;
        &lt;input
          type=&#39;password&#39;
          name=&quot;password&quot;
          placeholder=&quot;Password&quot;
        /&gt;
        &lt;button&gt;Submit&lt;/button&gt;
      &lt;/form&gt;
    &lt;/div&gt;
  );
}


export default LoginPanel;
function App({ loggedName }) {
  ... do what you need with the passed loggedName prop ...

  ...
}

export default App;

答案2

得分: 0

Use the name useState hook in the Main file and pass it as a props to the LoginPanel, Also pass the same hook to the App file to use the data inside.To switch between App and LoginPanel:- pass the isLogged hook to both of them and write a function inside both the files to switch when a button is clicked.

英文:

Use the name useState hook in the Main file and pass it as a props to the LoginPanel, Also pass the same hook to the App file to use the data inside.To switch between App and LoginPanel:- pass the isLogged hook to both of them and write a function inside both the files to switch when a button is clicked.

答案3

得分: 0

Thank you for help!
I changed the code.
It works and looks like that:

import React, { useState } from "react";

function LoginPanel({ onLogin }) {
    const [fname, setName] = useState({
        fName: "",
        password: "",
    });

    function handleChange(event) {
        const { name, value } = event.target;

        setName(prevValue => {
            return {
                ...prevValue,
                [name]: value
            };
        });
    }

    function login(event) {
        event.preventDefault();
        onLogin(fname.fName);
    }

    return (
        <div className="container">
            <h1>
                Log In 
            </h1>
            <form onSubmit={login}>
                <input
                    onChange={handleChange}
                    name="fName"
                    value={fname.fName}
                    placeholder="First Name"
                    required
                />
                <input
                    type='password'
                    name="password"
                    placeholder="Password"
                />
                <button type="submit">Submit</button>
            </form>
        </div>
    );
}

export default LoginPanel;
import React, { useState } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";

function App({ loggedName }) {
    const [notes, setNotes] = useState([]);
    function addNote(newNote) {
        setNotes(prevNotes => {
            return [...prevNotes, newNote];
        });
    }

    function deleteNote(id) {
        setNotes(prevNotes => {
            return prevNotes.filter((noteItem, index) => {
                return index !== id;
            });
        });
    }
    return (
        <div>
            <Header/>
            <h1>Hi {loggedName}</h1>
            <CreateArea onAdd={addNote} />
            {notes.map((noteItem, index) => {
                return (
                    <Note
                        key={index}
                        id={index}
                        title={noteItem.title}
                        content={noteItem.content}
                        onDelete={deleteNote}
                    />
                );
            })}
            <Footer />
        </div>
    );
}

export default App;
import React, { useState } from "react";
import App from "./App";
import LoginPanel from "./LoginPanel";

function Main() {
    const [isLogged, setLogged] = useState(false);
    const [loggedName, setLoggedName] = useState("");

    function handleLogin(name) {
        setLogged(true);
        setLoggedName(name);
    }

    return (
        <div>
            {!isLogged ? (
                <LoginPanel onLogin={handleLogin}/>
            ) : (
                <App loggedName={loggedName}/>
            )}
        </div>
    );
}

export default Main;
英文:

Thank you for help!
I changed the code.
It works and looks like that:

import React, { useState } from &quot;react&quot;;
function LoginPanel({ onLogin }) {
const [fname, setName] = useState({
fName: &quot;&quot;,
password: &quot;&quot;,
});
function handleChange(event) {
const { name, value } = event.target;
setName(prevValue =&gt; {
return {
...prevValue,
[name]: value
};
});
}
function login(event) {
event.preventDefault();
onLogin(fname.fName);
}
return (
&lt;div className=&quot;container&quot;&gt;
&lt;h1&gt;
Log In ↓
&lt;/h1&gt;
&lt;form onSubmit={login}&gt;
&lt;input
onChange={handleChange}
name=&quot;fName&quot;
value={fname.fName}
placeholder=&quot;First Name&quot;
required
/&gt;
&lt;input
type=&#39;password&#39;
name=&quot;password&quot;
placeholder=&quot;Password&quot;
/&gt;
&lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
);
}
export default LoginPanel;
import React, { useState } from &quot;react&quot;;
import Header from &quot;./Header&quot;;
import Footer from &quot;./Footer&quot;;
import Note from &quot;./Note&quot;;
import CreateArea from &quot;./CreateArea&quot;;
function App({ loggedName }) {
const [notes, setNotes] = useState([]);
function addNote(newNote) {
setNotes((prevNotes) =&gt; {
return [...prevNotes, newNote];
});
}
function deleteNote(id) {
setNotes((prevNotes) =&gt; {
return prevNotes.filter((noteItem, index) =&gt; {
return index !== id;
});
});
}
return (
&lt;div&gt;
&lt;Header/&gt;
&lt;h1&gt;Hi {loggedName}&lt;/h1&gt;
&lt;CreateArea onAdd={addNote} /&gt;
{notes.map((noteItem, index) =&gt; {
return (
&lt;Note
key={index}
id={index}
title={noteItem.title}
content={noteItem.content}
onDelete={deleteNote}
/&gt;
);
})}
&lt;Footer /&gt;
&lt;/div&gt;
);
}
export default App;
import React, { useState } from &quot;react&quot;;
import App from &quot;./App&quot;;
import LoginPanel from &quot;./LoginPanel&quot;;
function Main() {
const [isLogged, setLogged] = useState(false);
const [loggedName, setLoggedName] = useState(&quot;&quot;);
function handleLogin(name) {
setLogged(true);
setLoggedName(name);
}
return (
&lt;div&gt;
{!isLogged ? (
&lt;LoginPanel onLogin={handleLogin}/&gt;
) : (
&lt;App loggedName={loggedName}/&gt;
)}
&lt;/div&gt;
);
}
export default Main

huangapple
  • 本文由 发表于 2023年5月23日 00:08:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定