简体   繁体   中英

Manipulating dom elements dynamically in react?

I am trying to have a button change color when the user clicks it in React. Each button I am trying to add this functionality to is also updating state. How can I interact with styles AND update state when these buttons are clicked? Here's my crude attempt:

Some HTML:

<div className="searchPrivacyContainer">
            <p>USERS CAN SEARCH FOR MY PROJECT:</p>
            <div className="searchPrivacySelect">
              <div
                className="searchPrivacyYes"
                onClick={
                  (holdColor,
                  function () {
                    setProposal({ ...proposal, searchable: true });
                  })
                }
              >

And this is the most basic version of the function I'm trying to bind. Writing the body of the function should be the straightforward part hopefully, I just don't know how to bind it to the div which is already calling another function:

const holdColor = (event) => {
    console.log(event.target.style);
  };

I think this part isn't not working as you expecting,

onClick = {
  (holdColor,
    function() {
      setProposal({ ...proposal,
        searchable: true
      });
    })
}

Simple test,

 function x(ev){console.log('x', ev)} function y(ev){console.log('y', ev)} const listener = (x, y) listener(123)

Look, first one ( x ) never got called, So, you might wanna do something like this on your listener.

onClick={(ev) => {
  holdColor(ev)

  setProposal({ ...proposal,
    searchable: true
  });
}}

EDIT: see this working example (it might be helpful), https://codesandbox.io/s/eloquent-wilson-drbbk?fontsize=14&hidenavigation=1&theme=dark

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM