简体   繁体   中英

How to get JSX tag attributes in functional react?

I would like to understand how to access custom attributes to component tags in react. Unfortunately I couldn't find anything searching the internet because I couldn't find out what to search for so that I don't get only tons of sites that explain how to pass props to components.

I am using react-color and it sends me an object in "e" to handleChange function when something changes in the color picker.

const colorPicker = () => {
    return(
        <SketchPicker name="fill" onChange={handleChange} />
    );
}

With e.hex I can access the color in hex but how can I access the attribute "name"?

const handleChange = (e) => {
    console.log("handleChange", e);
    context.object().set({fill: e.hex}); //<- works
    //context.object().set({e.name: e.hex}); doesn't work <- e.name is undefined
}

According to the documentation, the onChange method can receive two arguments, the color (in your example, that is e ) and and event argument. Try accessing the second and see if the property is available in it. If it is, you're good to go, if it isn't:

Since react-color is a component you did not create from scratch, the only way to know how its props are handled is by checking its internal code and modify it if necessary. You will very likely not need/want to do that.

If the name property is very likely to be dynamic, pass it down to colorPicker and access it though props.name:

<SomeComponent>
  <ColorPicker name={'fill'}/>
</SomeComponent>

Then from within the ColorPicker component:

const handleChange = (e) => {
  context.object().set({[props.name]: e.hex}); 
}

By the way, if you are computing property names, you should use square brackets [] such as in the example above.

Hope this helps.

Try:

const handleChange = (e, target) => {
    console.log("handleChange", e);
    context.object().set({fill: e.hex}); //<- works
    context.object().set({target.name: e.hex});
}

It seems that react-color sends a second parameter into the handleChange function

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