【问题标题】:Functional radio component is not showing up as intended功能无线电组件未按预期显示
【发布时间】:2020-03-07 01:14:18
【问题描述】:

我正在使用功能组件创建自定义无线电组件。我让道具工作并且css工作但我看不到实际的“单选按钮”。

请查看我的代码 - 我在这里缺少什么。

type Props = {
  children: any,
  color?: string,
  size?: string,
}

const Radio = (props:Props) => {

  let radioClass = ''
    if(props.size === 'small') radioClass = 'radio-small';
    if(props.size === 'large') radioClass = 'radio-large';
    
    
    if(props.color === 'secondary') radioClass += ' radio-secondary';
    if(props.color === 'warning') radioClass += ' radio-warning';
    if(props.color === 'light') radioClass += ' radio-light';
    if(props.color === 'dark') radioClass += ' radio-dark';         

  return (
    <radio className={radioClass} > {props.children}</radio> 
  );
};

export default Radio
.radio-small  {
  font-size: 1.5em;
  
}


.radio-warning {
  color: red;
}

【问题讨论】:

    标签: javascript reactjs radio-button radio-group


    【解决方案1】:

    你可以这样做

    <input
      className={`radio-${props.size} radio-${props.color}`}
      type='radio'
    /> 
    

    【讨论】:

    • 这假定sizecolor 始终有效。 OP 的代码似乎在防御无效值。 (size 可能是必需的,但我认为 color 至少是可选的......可能是错误的。)
    【解决方案2】:

    HTML 中没有 radio 元素。有&lt;input type="radio"&gt;。另外,input 元素不能有子元素,所以你可能想要一个 label 来围绕它。

    所以它会是这样的:

    return (
        <label>
            {props.children}
            <input type="radio" className={radioClass} />
        </label>
    );
    

    旁注:您可以更简单地执行radioClass 的操作:

    const {size, color} = this.props;
    
    let radioClass = '';
    if (size === 'small' || size === 'large') {
        radioClass += `radio-${size}`;
    }
    
    if (color === 'secondary' || color === 'warning' || color === 'light' || color === 'dark') {
        radioClass += ' radio-${color}`;
    }
    

    或者,如果您知道props.sizeprops.color 将始终具有有效值,只需:

    const radioClass = `radio-${size} radio-${color}`;
    

    ...但是您的代码似乎在防止 sizecolor 缺席或无效。 (我假设至少color 是可选的。)

    【讨论】:

    • -$ 是什么意思?
    • @Fulano -$ 没有任何意义,破折号是文字。模板文字中的替换占位符${size}${color} 将这些变量的值放在那里。 radioClass += ` radio-${size}`; 等价于 radioClass += " radio-" + size;。更多:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多