0

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

  • If I bind this with handleChange then this refrence to Demo class and this.props.customProps gives undefined
  • If I do not bind this with handleChange then this.textValues is not defined and this.props.customProps gives perfect value

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

1
  • First of all never bind a function directly in render or any of life cycle methods. Do binding always inside constructor and call that reference in render. Commented Jan 22, 2018 at 3:37

2 Answers 2

1

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')
);

Sign up to request clarification or add additional context in comments.

2 Comments

Since TextInput is not a component he created there are so such things as the customPros. What he's trying to do is identify which textfield is changing and the way to do that is by using this prop onChange={this.handleChange('a')}, not sure how much better is could have answered the question.
Answer = code to fix the problem + explanation of the problem
0

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) {...}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.