Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - How to trigger an onClick event in react from a parent component to trigger its childs checkbox value?

I have a form with state handled in a context. within the form I have a checkbox component which I am trying to have its state handled within the context. So when I submit the form the checkbox returns a Boolean whether it is checked or not. I'm having trouble with the event handler triggering the checkbox. I have a number of textfields in the form which are behaving as expected and their values can be seen in the Db once the form is submitted.

Within the checkbox component the actual input is hidden for styling purposes. So the user will be clicking on the label(which is styled to look like a checkbox) or a secondary label (acting as a label)

I'd like it so that when a user clicks on either of the labels the checkbox is triggered. I had the onClick on the checkbox input but seeing as it's display is hidden the user cannot trigger the event. If I put the onClick on either of the labels or a parent element my onChange functions e.target is pointing to the wrong location.

Is there a way to pass in the the input as the e.target? if the onClick event is on the outer div?

onChange (within RecordForm.js)

  const onChange = (e) => {
      setRecord({ ...record, [e.target.name]: e.target.value });
  };

Checkbox.js

const CheckBox2 = ({ value, label, name, onChange }) => {
  return (
    <CheckBoxContainer onClick={onChange}>
      <LabelContainer>
        <CheckboxInput
          type='checkbox'
          value={value}
          name={name}
        />
        <CheckBoxLabel>
          <Tick className='Tick' />
        </CheckBoxLabel>
      </LabelContainer>
      <VisibleLabel>{label}</VisibleLabel>
    </CheckBoxContainer>
  );
};

export default CheckBox2;
question from:https://stackoverflow.com/questions/65644176/how-to-trigger-an-onclick-event-in-react-from-a-parent-component-to-trigger-its

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...