简体   繁体   English

在 onClick 触发器之后创建反应组件的最佳方法是什么(好的做法?)?

[英]What's the best way (good practice !) to create a react component after an onClick trigger?

I just start learning by myself Reactjs and I'm facing a problem.我刚开始自己学习Reactjs ,我遇到了一个问题。 I'm stuck and I would like to know how can I achieve to create a new <div> in the DOM when I click on a button.我被卡住了,我想知道当我单击一个按钮时如何在DOM中创建一个新的<div>

In pure JS, I used an addEventListener on a button then I add / remove css style of my to display it (before that, the <div> was hidden) with classList .在纯 JS 中,我在按钮上使用了addEventListener ,然后我add / remove css 样式以使用classList显示它(在此之前, <div>被隐藏)。 I presume that is not a best practice to implement it in Reactjs.我认为这不是在 Reactjs 中实现它的最佳实践。

So, I would like to know how to do that.所以,我想知道如何做到这一点。

Here is my first component.这是我的第一个组件。

const Welcome = () => {
    return (
        <div className="top">
          < Intro/>
          < InputUserName/>
          // Here, I need to build a new <div> only when I click on the following button (inside InputUserName)
        </div>
    )
};

Here is my second component with the button and the onCLick function.这是我的第二个带有按钮的组件和 onCLick function。

const InputUserName = () => {
    const [username, setUsername] = useState('');
    return (
        <div className="usernameField">
            <div className="userField flex">
              <input
                type="text"
                name="username"
                className="userID"
                placeholder="Discogs' Username"
                value={username}
                autoComplete="off" autosuggest="off"
                onChange={(e) => setUsername(e.target.value)}>
                    {console.log(username)}
            </input>
                <span
                    className="usernameButton btn"
                    onClick={() => handleSubmitUserName(username)}>Send
                </span>
            </div>
        </div>
    )
};

And finally, here is my function called when I click on the SEND button最后,这是我点击发送按钮时调用的 function

const handleSubmitUserName = (username) => {
    // Username field is empty !
    if (username === '') { 
        document.querySelector('.userID').style.border = "2px solid red";
    }
    // Username is !empty.
    // I need to build the following stuff inside the first component (the Welcome one). 
        return (
            <div className="hi">
                <p className="first">Hi <span class="pseudo">${username}</span>.</p>
                <p className="second">Let me find your next listening.</p>
            </div>
        )
};

There are a couple of ways to do it, but probably the simplest is to add a state member to Welcome which says whether to have the div or not, and have Welcome conditionally render the div based on that state member.有几种方法可以做到这一点,但可能最简单的方法是将 state 成员添加到Welcome中,该成员表示是否有div ,并让Welcome根据该 state 成员有条件地呈现div You have Welcome pass InputUserName a function to call to update the state member, and have InputUserName call that function appropriately.您有Welcome通过InputUserName和 function 来调用以更新 state 成员,并让InputUserName适当地调用 function。

Here is what you need to do这是您需要做的

const Welcome = () => {
  const [toggle, setToggle] = useState(false);
  const handleClick = () => setToggle((v) => !v);
  return (
    <div className="top">
      <button onClick={handleClick}>toggle the div</button>
      <Intro />
      <InputUserName />
      {toggle && <div>this would be visible when toggle is true</div>}
    </div>
  );
};

Basically you're looking to pass a value from a child component to a parent component.基本上,您希望将值从子组件传递到父组件。 Here's one way of doing it.这是一种方法。

We want to notify the "Welcome" component when the username has been submitted from the "InputUserName" component, so we're going to make an "onUsernameSubmitted" function.当用户名从“InputUserName”组件提交时,我们想通知“Welcome”组件,所以我们将创建一个“onUsernameSubmitted”function。

const Welcome = () => {
   
   const [username, setUsername] = useState("");
   const [showMyDiv, setShowMyDiv] = useState(false);
   const handleUsernameSubmitted = (username) => {
      setUsername(username);
      setShowMyDiv(true);

   }

    return (
        <div className="top">
          < Intro/>
          < InputUserName onUsernameSubmitted={(username) => handleUsernameSubmitted} />
          {showMyDiv && <div>Your custom div will appear here</div>}
        </div>
    )
};

Then in this line const InputUserName = (props) => { notice that I've just added the "props" argument.然后在这一行const InputUserName = (props) => {请注意,我刚刚添加了“props”参数。 Then in your handle function inside this component, call props.onUsernameSubmitted(username)然后在你的句柄 function 这个组件里面,调用props.onUsernameSubmitted(username)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调整大小后获取 React 组件宽度的最佳做法是什么? - What is the best practice to get the width of a React component after it's been resized? 在React中创建组件参数的最佳方法是什么? - What is the best way to create parameter of the component in React? 快速试用 React 组件的最佳实践是什么? - What's best practice to quickly try out a React component? 为 React 和 Preact 创建组件库的最佳方法是什么? - What is the best way to create component library for both React and Preact? React + Redux - 在表单组件中处理CRUD的最佳方法是什么? - React + Redux - What's the best way to handle CRUD in a form component? 为可重用的 React 组件存储全局变量的最佳方法是什么? - What's the best way to store a global variable for a reusable React component? 什么是最佳实践导航反应原生 - what's the best practice navigation react native 使用 react 调用 API 的最佳实践是什么 - What's the best practice to call API with react 创建自定义GeoJSON组件的好方法是什么 - What is the good way to create custom GeoJSON component 将 React 组件注入另一个 React 组件的最佳方法是什么? 还是我应该打扰? - What's the best way to inject a React component into another React component? Or should I bother?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM