Is there any way to make a component listen to a React Native function?

Asked

Viewed 176 times

1

I need to make a bind to a function that returns me if an item is marked or not, however the function that returns me this is only executed once, there is a way to bind to that function?

<List dataArray={this.state.talhoes}
        renderRow={(talhao) =>
      <TouchableOpacity onPress={() => this.select(talhao)}>
        <Card>
          <CardItem>
            <Thumbnail square size={40} source={{ uri: talhao.public_url_screenshot }} />
            <Text style={{ paddingLeft: 10 }} > {talhao.name}  </Text>
            <Right>
              <CheckBox checked={this.checkSelected(talhao)} /> //Aqui o problema
            </Right>
          </CardItem>
        </Card>
      </TouchableOpacity>
    }>
  </List>
  • Have you tested checked={this.checkSelected.bind(this, talhao)} and then use checkSelected(talhao, event){?

  • @Sergio doesn’t work, give me the answer that he expects a Boolean

  • Felipe: I saw now that this checkbox is a component. What is the library? should have a onChange you can use like you were using with the checked. That one checked shall be the state of the component propType requires to be a Boolean..

1 answer

0

You must assign a value from state of your component or a property that is updated externally, because you need the method render of your component is executed so that the change appears on the screen.

An example of how to solve this in a simple way:

// Seu metodo checkSelected, pode alterar o state em vez de retornar o valor a ser definido no <CheckBox/>
checkSelected (value) {
  // exemplo hipotético ok?
  const checked = value !== undefined
  this.setState({ checked })
}

// Quando o state é alterado, o método render é executado e o valor de checked será atribuido corretamente de acordo com o estado atual
<CheckBox checked={this.state.checked)} />
  • I think you made a small mistake related to the logic of the original example. Who should modify the state component is the select(talhao), which runs on the event Handler onPress of TouchableOpacity. So the call of checkSelected(talhao) can continue where you are.

  • 1

    All right, it was just a very simple example, the idea was to strengthen the use of setState and the assignment of state p/ update the component ;)

Browser other questions tagged

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