首页 > 解决方案 > 如何在输入标签(这是一个组件)中处理“autoFocus”和“required”属性?

问题描述

class Inputfield extends Component {
    render() { 
        return ( 
            <>
                <label className={classNames('textfield-outlined', this.props.className)}>
                    <input 
                      name={this.props.name}
                      value={this.props.value}
                      type={this.props.type} 
                      placeholder=" " 
                      onChange={this.props.onChange}
                      autoComplete={ this.props.autoComplete ? "on" : "off"}
                      />
                    <span>{this.props.label}</span>
                </label>
            </>
         );
    }
}

Inputfield.defaultProps={
   type:"text",
   label:"Enter the name of field",
   autoComplete: true,
}

Inputfield.propTypes={
    name: PropTypes.string.isRequired,
    type: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    className: PropTypes.string,
    onChange: PropTypes.func,
    autoComplete: PropTypes.bool
}

这是输入组件,如何处理这个组件中的autoFocus属性,它是作为props传递的?autoFocus="on" 或 "of"、autoFocus="true" 或 "false" 不起作用...!。tq 提前。

标签: reactjsreact-componentreact-create-app

解决方案


您可以使用 autoFocus 属性来自动聚焦输入元素,我认为您将 prop 作为字符串传递,尝试为 autoFocus 传递布尔值并像这样使用它

return ( 
        <>
            <label className={classNames('textfield-outlined', this.props.className)}>
                <input 
                  name={this.props.name}
                  value={this.props.value}
                  type={this.props.type} 
                  placeholder=" " 
                  onChange={this.props.onChange}
                  autoComplete={ this.props.autoComplete ? "on" : "off"}
                  autoFocus={this.props.autoFocus ? true : false} // boolean value
                  />
                <span>{this.props.label}</span>
            </label>
        </>
     );

你也可以使用Ref来聚焦一个元素,

希望能帮助到你


推荐阅读