reactjs - 如何在这些代码中执行正确的 useState?
问题描述
我的渲染有问题,所以我被告知将我使用的表设置为状态,以便数据可以正确更新。
我正在使用的表:
<ScrollView horizontal={true} style={{ marginTop: 20 }}>
<View>
<Table borderStyle={{ borderWidth: 1, borderColor: '#C1C0B9' }}>
<Row
data={this.state.tableHead}
widthArr={this.state.widthArr}
style={styles.header}
textStyle={styles.text}
/>
</Table>
<ScrollView style={styles.dataWrapper}>
<Table borderStyle={{ borderWidth: 1, borderColor: '#C1C0B9' }}>
{this.state.tableData.map((rowData, index) => (
<Row
key={index}
data={rowData}
widthArr={this.state.widthArr}
style={[styles.row, index % 2 && { backgroundColor: '#F7F6E7' }]}
textStyle={styles.text}
/>
))
//this.state.myState
}
</Table>
</ScrollView>
</View>
</ScrollView>
它正在工作render()
,我尝试setState
onPress
选择激活它,我做了类似的事情:
updateState = () =>
this.setState({
myState: this.state.tableData.map((rowData, index) => (
<Row
key={index}
data={rowData}
widthArr={this.state.widthArr}
style={[styles.row, index % 2 && { backgroundColor: '#F7F6E7' }]}
textStyle={styles.text}
/>
)),
})
但不能让它工作。
解决方案
添加一个toggle
状态。此状态将在每个onPress
事件上发生变化。
(对于下面的示例,我正在使用onClick
)
const {useState} = React;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
toggle: false,
};
this.data = [1, 2, 3, 4];
}
render() {
return (
<div>
<button onClick = {
() => this.setState({ toggle: !this.state.toggle })
}>
{this.state.toggle ? 'hide' : 'show'}
</button>
{this.state.toggle ? this.data.map(d => (
<div>{d}</div>
)) : null}
</div>
);
}
}
ReactDOM.render(
<App /> ,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
推荐阅读
- python-2.7 - 改善曲线拟合日志
- java - Debian 的 Docker 映像:拒绝访问文件或目录“/usr/local/openjdk-8/bin/java”
- python - 旨在使用 JSON、请求和 gtts 发送音频消息的 Python VK 聊天机器人不起作用
- ios - SwiftUI 文本对齐
- python - 具有双索引的 Pandas 查询
- apache - Azure VM 上的 appache2 服务器出现错误:“无法访问此站点 *.*.*.*”
- javascript - 类型错误:object.function 不是函数
- python - 如何使用 selenium webdriver 将现有登录令牌用于电报 Web
- javascript - 为什么我的 API 调用应该随机接收重复数据?
- arrays - 具有多个 VAR 选项的 SAS 转置表