Rajat Sharma
Rajat Sharma

Reputation: 57

Give Custom props to TextInput and use it on event handlers

I'm new to react native and trying event handling and came up with a problem.

Suppose I have a code like this

class Demo extends React.Component {
  constructor(props) {
    this.textValues = {a: null, b: null};
  }

  handleChange(event) {
    this.textValues['a'] = this.props.customProps;
    this.textValues['b'] = event.nativeEvent.text;
  }

  render() {
    return (
      <View>
        <TextInput
          customProps = 'T1'
          onChange = {this.handleChange.bind(this)}
        />
        <TextInput
          customProps = 'T2'
          onChange = {this.handleChange.bind(this)}
        />
      </View>
    )
  }
}

I want to access textValues from parent component i.e., Demo as well as customProps from TextInput but

But I want to acess both textValues of Demo and customProps of TextInput in handleChange function.

Upvotes: 0

Views: 109

Answers (2)

yangguang1029
yangguang1029

Reputation: 1823

do you want the handleChange function to know which TextInput is called from?

try these codes

<TextInput
    customProps = 'T1'
    onChange = {(input)=>{
         this.handleChange("T1", input)
      }}
 />
 <TextInput
      customProps = 'T2'
      onChange = = {(input)=>{
         this.handleChange("T2", input)
      }}
 />

and the hanleChange function is

 handleChange(inputTag, inputText) {...}

Upvotes: 0

Davi DeBarros
Davi DeBarros

Reputation: 368

class Demo extends React.Component {
  constructor(props) {
	  super(props);
    this.textValues = { a: null, b: null };
  }

  handleChange = field => (event) => {
	  console.log(field)
    this.textValues[field] = event.nativeEvent.text
  }

  render() {
    return (
      <View>
        <TextInput onChange={this.handleChange('a')} />
        <TextInput onChange={this.handleChange('b')} />
      </View>
    )
  }
}

ReactDOM.render(
  <Demo />,
  document.getElementById('container')
);

Upvotes: 1

Related Questions