bind( ) in Javascript / React - Doubt

Asked

Viewed 209 times

0

why do I necessarily need to bind() a function within a constructor? type:

constructor (props){

   super(props);

   this.funcao = this.funcao.bind(this);
}

Couldn’t do this bind() without the builder?

2 answers

1

You could do in render, but, as render is always called when some upgrade occurs, for performance reasons, the ideal is to do in the constructor. You could also use an Arrow Function, but would eventually fall into the above problem. An example using Arrow Function

class Home extends Component {
  onCardPress = (message) => {
    alert(message)
  }
  render() {
    return (
      <View>
        <Card
          onCardPress={this.onCardPress}
          message="Hello world!"
        />
      </View>
    )
  }
}

class Card extends Component {
  onClick = () => {
    const { message, onCardPress } = this.props;
    onCardPress(message);
  };
  render() {
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={this.onClick}
      />
    )
  }
}

Here’s a text that explains better how bind works

https://medium.com/shoutem/react-to-bind-or-not-to-bind-7bf58327e22a

  • Thank you Bins, if you can look my answer above... and please correct me

0

Then I’d have no problem doing it like this?

export default class App extends Component{


state = {
    texto: ''
}

this.alteraStatus = this.alteraStatus.bind(this);

alterarStatus = (t)=>{
    this.setState({texto: this.state.texto = t});
}

render(){
    return(
        <View>
            <TextInput style={styles.input} placeholder='Qual é o seu nome?' onChangeText={this.mudarTexto}></TextInput>

            <Text style={styles.texto}>{this.state.texto}</Text>

        </View>
    );
}
}
  • I believe that your code above would not work because it is out of context. And if the bind was in render context it can be called many times, as it should come in the constructor. About bind I found a link that can help you understand better. https://tableless.com.br/react-this-bind-so-que-thus/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.