【问题标题】:setState and icon not working together - React NativesetState 和图标不能一起工作 - React Native
【发布时间】:2020-09-15 05:48:52
【问题描述】:

在我的 React Native App 中,我有一个简单的 FlatList。 Flatlist 的渲染项是一个组件“SearchItem.js”
每次调用我的组件时,我都需要重新初始化该组件内的状态。

平面列表

                       <FlatList
                        ListFooterComponent={<View style={{ paddingBottom: 30 }}></View>}
                        data={temp}
                        keyExtractor={(item) => item.id}
                        renderItem={this.renderItem.bind(this)}    //SearchItem component                    
                        />

渲染项目:

renderItem({item}) {

              return <SearchItem item={item}
                            onPress={() => {this.goToDetails(item)} 
                      ]  /> ;
            }

单击向下箭头图标,消息将展开。点击“^”,它就会折叠起来。

下面的 SearchItem 组件。每次调用组件时,此处状态“arrowClicked”都需要为 false。如果我们单击箭头图标并展开消息,则状态变为“真”。每次调用组件时,如何将状态重新初始化为“false”。目前,如果消息被展开,它会保持展开状态。再次调用组件时,它应该会自动折叠。

export default class SearchItem extends Component {

constructor(props) {
    super(props)

    this.state = {
     arrowClicked: false
    }
   }

setFullLength(bool){
    this.setState({
      arrowClicked: bool
    })
  }
.
.
render(){

return (

    {
      arrowClicked === true ? 
     <Icon type='materialicons' name='keyboard-arrow-up' onPress={()=>{this.setFullLength(false)}}  />
          : 
     <Icon type='materialicons' name='keyboard-arrow-down' onPress={()=>{this.setFullLength(true)}}  />

      }

 )
}

如何重新初始化我的状态 arrowClicked = "false" ????请帮忙!!!

更新: 其实很奇怪!!

示例:假设我在我的平面列表渲染中搜索“你好”和 2 个项目。我单击其中一条消息上的箭头图标,消息就会展开。现在我清除搜索栏中的“你好”文本。 Flatlist 再次呈现并显示所有项目。我的消息仍在扩展中(状态:真)。现在我在我的平面列表渲染中搜索另一个文本“hi”和 2 个非常不同的项目。我清除搜索文本“hi”。 Flatlist 再次呈现。现在我之前展开的消息已折叠(状态恢复为 false)。如何???????焦点问题??????

【问题讨论】:

  • 请使用setFullLength 方法更新您的问题。
  • 使用 setFullLength 方法更新。
  • @RakshaHegde 在您的问题中“每次调用我的组件”是什么意思?
  • 我有一个具有搜索逻辑的 TextInput。我输入“hello”,它会在我的 FlatList 中搜索“hello”。在我的平面列表中,“renderItem”是一个组件 (请参阅我的代码)。这个组件会被多次调用 SOOO。
  • 你有没有试过这个:- setFullLength(){ this.setState({ arrowClicked: !this.state.arrowClicked }) }。并且 onPress 不传递任何布尔标志...

标签: javascript reactjs react-native icons state


【解决方案1】:

你需要从状态调用arrowClicked;

render() {
const { arrowClicked  } = this.state;
const icon1 = <Icon type='materialicons' name='keyboard-arrow-up' onPress={()=>{this.setFullLength(false)}}  />;
const icon2 = <Icon type='materialicons' name='keyboard-arrow-down' onPress={()=>{this.setFullLength(true)}}  />;
return (
    <Fragment>
      {arrowClicked ? icon1 : icon2}
    </Fragment>
 )
}

【讨论】:

  • 我猜她想重新初始化状态,不是无法控制状态?
  • 是的,这不起作用!!!它没有重新初始化。我单击箭头图标并将状态更改为“true”。它不会再次变成“假”!!!
【解决方案2】:

好的,解决方案是添加一个 Key,因为这是功能比较,而不是纯。 我刚刚向我的 FlatList 的父级添加了一个密钥,它起作用了!!!

【讨论】:

  • 如果将来有人遇到类似问题,也许发布您的代码区域会更好。并选择它成为答案。
猜你喜欢
  • 2020-08-21
  • 1970-01-01
  • 2016-10-02
  • 2020-07-10
  • 2021-10-01
  • 2021-03-29
  • 2014-06-30
  • 1970-01-01
  • 2018-12-23
相关资源
最近更新 更多