繁体   English   中英

将值从类方法传递到React组件

[英]Pass value from class method to a react component

情况:我有一个带有自己方法的类。 此类在React组件中实例化。

我需要什么:在类中的一种方法中,它使用.val()更改输入( this.$el )的值,但是我正在通过.val()侦听此输入的更改。 onChange 我需要将用于设置输入值的值(通过this.$el.val(value) )传递给React组件以更改其状态。

我尝试过的.change() 我尝试将.change()trigger('change')val(value) ,但这没有任何影响。

因此,当在class方法中设置它时,我需要能够访问我在React组件的.val(value)中使用的.val(value) 我考虑过使用一个方法并在componentWillUpdate上调用该方法,但是该组件不会更新,因为通过val()设置输入值不会触发更改。

有任何想法吗?

组件代码:

// Create a ref to manage blur/focus state on the search input
this.inputRef = React.createRef()
// Setup initial state
this.state = {
  supersearchResults: [],
  value: this.props.initialValue || ''
}
this.onInputChange = this.onInputChange.bind(this)

tag('input', {
      autoComplete: 'off',
      className: blockElement('search-input'),
      onChange: this.onInputChange,
      placeholder: 'Find people, collections and pages',
      ref: this.inputRef,
      type: 'text',
      value: this.state.value
 })

类代码: this = thisthis.$el =输入

// What is happening:
// A user types in an input, suggestions display in a list, when you
// select a suggestion, it calls the below to change the input value
this.$el.val(complete)
this.$el.blur()
this.hide()

如果我理解正确,则希望能够访问html字段的值。 然后,请考虑以下注意事项。 使用受控输入,以便

class ReactComponent extends...
    constuctor (props) {
        super();
        this.state = { fieldValue: props.fieldValue || '' };
    }

    onFieldChange = (event) => {
       this.setState('fieldValue': event.currentTarget.value)
    }

    render () {
        return (
           <div>
                <input type="text"
                    value={this.state.fieldValue}
                    onChange={this.onFieldChange}
                >
           <div>
        )
    }
}

现在有了这些代码,以防万一您需要使用一些外部类来调用某些代码,只需将其正确地放入生命周期中即可。 但是为了引用该值,请使用组件状态。 并且如果您要以编程方式想要更改值,请执行相同的操作以更新状态中的值。 如果我错过了什么,请在评论中告诉我。

您需要将状态保留在类组件中。 考虑以下

class TextExample extends Component{
  constructor(){
    super(props);
    this.state ={
      username: null
    }
    this._handleChange = this._handleChange.bind(this);
  }

  _handleChange(e){
    const { name, value } = e.target;
    this.setState({ username: value}) // for single TextField
    // if you want to reuse this _handleChange function for all the TextFields then you need to use the below commented code which updates state of current TextField

   //this.setState({ [name]: value })  // it is similar like the JSON bracket notation 
  }

  render(){
    return(
      <div>
        <TextField
          id="username"
          label="Username"
          name="username"
          value={this.state.username}
          onChange={this._handleChange}   // it will call the _handleChange function on every keypress inside the TextField. 
        />
      </div>
    )
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM