简体   繁体   English

我如何定位被点击的 React 组件

[英]How do i target React component which is clicked

I want to change the class of a component when clicked.I use state to create a new component with the properties of name and done(which is upon creation false).Then this is pushed into the todos array.我想在单击时更改组件的 class。我使用 state 创建一个具有 name 和 done 属性的新组件(在创建时为 false)。然后将其推送到 todos 数组中。 Now the question is how do I find which component is clicked and change its "done" property to?done ?现在的问题是如何找到单击了哪个组件并将其“完成”属性更改为?完成?

function App() {
    const [todos, setTodos] = useState([])
    const [newTodo, setNewTodo] = useState({
        name: "",
        done: false
    })

    const handleInput = (event) => {
        setNewTodo({name: event.target.value})
    }

    const handleDone = (event) => {

        //WHAT TO DO HERE

    }
    


    const submitTodo = (event) => {
        event.preventDefault();
        setTodos([...todos, newTodo.name])
        console.log(newTodo.name)
        setNewTodo({name: ""})
    }

  return (
    <div className="App">
        <form onSubmit={submitTodo}>
            <input onChange={handleInput} value={newTodo.name}/>
            <button>Add Todo!</button>
        </form>


        <ul>
            {todos.map(todo => (
                <li className={/*Change the class based on the DONE property*/} onClick={handleDone}>{todo}</li>
            ))}
        </ul>

    </div>
  );
}

export default App;

change your newTodo state更改您的新Todo state

const [newTodo, setNewTodo] = useState('');
const [show,setShow] = useState(false);


const handleDone = (event) => setShow(!show)

.....
.....
.....

<li className={show ? 'classname when show is true': 'classname when show is false'} onClick={handleDone}>{todo}</li>


First of all, you should consistently make your todos contain both name and done properties.首先,您应该始终如一地让您的待办事项同时包含namedone属性。 Having this you just pass the todo from the clicked <li> to your click handler so it can modify its done property and cause rerender by updating todos state.有了这个,您只需将点击的<li>中的 todo 传递给您的点击处理程序,以便它可以修改其 done 属性并通过更新todos state 来导致重新渲染。

function App() {
    const [todos, setTodos] = useState([])
    const [newTodo, setNewTodo] = useState({
        name: "",
        done: false
    })

    const handleInput = (event) => {
        setNewTodo({name: event.target.value, done: false }); // this now adds done property
    }

    const handleDone = (todo) => {
        todo.done = !todo.done;
        setTodos([...todos]); // This sets new todos to cause a rerender with updated list
    }
    
    const submitTodo = (event) => {
        event.preventDefault();
        setTodos([...todos, newTodo]) // this now appends entire newTodo item not only it's name
        setNewTodo({name: "", done: false}) // this now also sets default done
    }

  return (
    <div className="App">
        <form onSubmit={submitTodo}>
            <input onChange={handleInput} value={newTodo.name}/>
            <button>Add Todo!</button>
        </form>

        <ul>
            {todos.map(todo => (
                <li
                    className={todo.done ? 'classA' : 'classB'}
                    onClick={() => handleDone(todo)}
                >
                    {todo.name} // this now displays todo.name not todo
                </li>
            ))}
        </ul>

    </div>
  );
}

export default App;

Additionally you could extract todos and the click handler into a separate component:此外,您可以将待办事项和点击处理程序提取到单独的组件中:

function ToDo({ item }) {
   const [clicked, setClicked] = useState(item.done);

   const handleClick = useCallback(() => {
       item.done = !clicked
       setClicked(!clicked);
   }, [clicked]);

   return <li
       className={clicked ? 'classA' : 'classB'}
       onClick={handleClick}
   >
       {item.name}
    </li>;
}

Then just render a list of components with your App component:然后只需使用您的 App 组件呈现组件列表:

<ul>
    {todos.map(todo => <ToDo item={todo} />
</ul>

暂无
暂无

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

相关问题 React - 如何检测是否单击了子组件 - React - How do I detect if a child component is clicked 如何在我的 class 组件中检测在功能组件中单击了哪个输入值? - How do I detect in my class component which input value's clicked in functional component? 如何在 React 组件中定位特定节点并在组件被重用时具有独立的行为? - How Do I Target A Specific Node In React Component and Have Independent Behavior When Component is Reused? 在 React Navigation v3 中单击 React Native 中 bottomTabNavigator 上的选项卡时,如何刷新我的组件? - How do I refresh my component when clicked on tab on bottomTabNavigator in React Native, in React Navigation v3? 如何在React中将单击的组件中的数据从一条路径传递到另一条路径? - How do I pass data from a clicked component from one Route to another in React? 如何将用户在本地存储中单击的按钮的 ID 存储在 React 组件中? - How do I store the id of a button a user clicked in local storage in a react component? 我怎么知道点击了哪个元素? - How do I know which element was clicked? 反应日期时间; 我正在使用二合一组件,我如何分辨哪个是哪个? - React-Datetime; I'm using two in one component, how do I tell which is which? 如何根据在 React 中单击哪个按钮来切换 div class? - How do I toggle div class depending on which button has been clicked in React? 如何测试在其父级上调用函数的 React 组件,这会更改组件上的 props? - How do I test a React component that calls a function on its parent, which changes props on the component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM