如何使用Useref / EventTarget根据组件的子节点设置组件的prop?

时间:2020-11-12 12:45:41

标签: javascript reactjs react-hooks

我要实现的方法是单击每个圆圈,然后选中单选按钮,然后将Avatar的prop'border'设置为true(如下面的代码所示)。我实现了第一个目标,但后一个运气不好。有什么好办法做到这一点?

import React, { useState, useRef } from 'react';
import { Field, ErrorMessage } from 'formik';
import FormikError from '../FormikError';
import Avatar from '../../../../atoms/avatar/avatar';
import Icon from '../../../../atoms/icon/icon';

const FormikRadio = ({ label, name, options, ...rest }) => {
    const [selected, setSelected] = useState('');
    const inputRef = useRef();

    const handleClick = (e) => {
        e.currentTarget.childNodes[1].checked = true;
        console.log(inputRef);
        setSelected(e.currentTarget);
    };

    return (
        <div className='form-control radio-group'>
            <Field name={name} {...rest}>
                {({ field }) => {
                    return options.map((option) => {
                        return (
                            <React.Fragment key={option.key}>
                                <Avatar onClick={(e) => handleClick(e)} ref={inputRef}>
                                    <Icon variant='AVATAR_KIWI' />
                                    <input
                                        type='radio'
                                        id={option.value}
                                        {...field}
                                        value={option.value}
                                        checked={field.value === option.value}
                                        border={I want this conditionally set if radio checked is true}
                                    />
                                </Avatar>
                            </React.Fragment>
                        );
                    });
                }}
            </Field>
            <ErrorMessage name={name} component={FormikError} />
        </div>
    );
};

export default FormikRadio;

1 个答案:

答案 0 :(得分:0)

您可以设置border = {selected.childNodes [1] .id === option.value}

此外,您可以使用ID作为选择

<input
   type='radio'
   id={option.value}
   {...field}
   value={option.value}
   checked={field.value === option.value}
   border={selected.childNodes[1].id === option.value}
/>