美文网首页YAOPAI 团队博客
React Button/InputGroup 组件使用栗子🌰

React Button/InputGroup 组件使用栗子🌰

作者: Yi罐可乐 | 来源:发表于2016-06-12 09:50 被阅读288次

    Button

    export const ButtonBlock = ({buttonType, value, handleSubmit}) => (
      <div className="btn-block" onClick={handleSubmit}>
        <a className={`btn ${buttonType}`} href="javascript:void(0);">
          {value}
        </a>
      </div>
    )
    

    InputGroup

    const InputGroup = props => {
    //请注意下面的 ...others
      const { iconLeft, iconRight, updateValue, ...others } = props
      return (
        <section className="input-group-dark">
          <i className={`icon icon-left ${iconLeft}`} />
          <input
            className="input input-block"
            onChange={event => updateValue(event.target.value.trim())}
            /*...others 不明白的话翻一下 ES6 工具书*/ 
            {...others}
          />
          {iconRight ? <i className={`icon icon-right ${iconRight}`} /> : ''}
        </section>
      )
    }
    

    引入不同

    import { ButtonBlock } from '...Button';
    import InputGroup from '....InputGroup';
    

    因为 Button 组件可能会弄好几个 button ,不确定

    栗子🌰

    class LoginForm extends React.Component {
      constructor(props){
        super(props);
        this.state = {
          userName : '',
        }
        this._handleLogin = this._handleLogin.bind(this)
      }
    
       _handleLogin() {
         let userName = this.state.userName;
         //点击提交按钮可以拿到输入框里的值
      }
      render() {
        return (
          <InputGroup
                iconLeft="phone"
                updateValue={ userName => this.setState({userName}) }
                type="tel"
                pattern="[0-9]*"
                placeholder="请输入手机号"
                // type,pattern,placeholder 这些属性可以随意添加,因为 InputGroup里有{...other}
            />
          <ButtonBlock
                buttonType="btn-dark"
                value="立即登录"
                handleSubmit={this._handleLogin}
            />
      )
    

    可以不用 this.state 吗?

    可以!
    updateValue={ userName => this.setState({userName}) }
    反正输入框的值 userName 已经拿到,我猜可以这么写(未测试):

      submit(value) {
        console.log(value)
      }
      render() {
        let value;
        return (
          <form submit={() =>this.submit(value)}>
            <InputGroup
                iconLeft="phone"
                updateValue={ userName => value  = userName  }
                type="tel"
                pattern="[0-9]*"
                placeholder="请输入手机号"
              />
          </form>
      )
    
    

    相关文章

      网友评论

        本文标题:React Button/InputGroup 组件使用栗子🌰

        本文链接:https://www.haomeiwen.com/subject/xtyedttx.html