reactjs – 如何重新渲染React Native中的所有内容
我的应用程序具有通过REST API提供的主题(颜色和样式).每当在服务器上更改主题时,应用程序都会通过套接字通信获得通知,因此它可以通过REST获取新主题.
主题是在Redux Saga中获取的,颜色被保存到Redux商店(以便能够持久保存到磁盘)以及我可以从任何地方到达的“全局”单例对象,即使是非连接组件. 当一个新主题到来时,我想重新渲染应用程序中的每个元素.我设法以一种hacky方式重新渲染所有连接商店的组件 – 通过注入一个虚拟属性,当新的主题被更改时,该属性会发生变化. 有没有办法强制更新整个应用程序? 问题领域: >哑组件(不知道主题变化) 这是一个hacky force-re-render of react-navigation的例子: myAppContainer.render() { <AppRouter screenProps={this.props.styling} /> } 即我的AppContainer通过mapStateToProps获取this.props.styling.包装的StackNavigator通过screenProps获取此信息,当商店获得新的样式数据时,它会强制导航器重新渲染. 我不想继续这条hacky路径.相反,我想要一个forceUpdateEverything()函数,我可以从我的AppContainer调用它.有这样的事吗? 编辑以评论@bennygenel的答案: 我认为Benny所描述的基本上就是我所做的. this.props.styling中的更改会触发重新渲染. 但是我必须将这个实现到所有组件中并通过其screenProps“hack”反应导航,如我所述.这是我希望避免的,但我想我必须走很长的路. 我正在使用immutable.js,所以发送完整的样式而不仅仅是主题名称没什么大不了的,因为它只是一个指针,可以快速地与它的前值进行比较以寻找变化. 我没有让forceUpdate()工作,而不是调用它所调用的组件.我认为它不会通过所有孩子递归传播.
我认为这样做的最简单和最高性能的方式,然后将所有样式对象保存在您的状态和redux中,您可以只保留某种主题标识符.这种方式可以应用组件使用的主题发生任何更改.
在反应中有一种叫做 来自反应文件;
我认为你应该做的是在你的应用程序中创建一个主题逻辑并相应地更改主题. 例 // styles.js const styles = { button: { blue: { backgroundColor: 'blue' },red: { backgroundColor: 'red' },green: { backgroundColor: 'green' } } }; export default styles; // Dumb component example import styles from './styles'; const Button = (props) => { return <Button {...props} style={[props.style,styles.button[props.theme]]} /> }; // Complex component example import styles from './styles'; export default Button extends React.Component { constructor(props) { super(props); } render() { const {style,theme} = this.props; return <Button {...this.props} style={[style,styles.button[theme]]} /> } } // usage in another component import React,{ Component } from 'react'; import { Text,View,StyleSheet } from 'react-native'; import Button from './components/Button'; // Custom button component import styles from './styles'; export default App extends React.Component { constructor(props) { super(props); } render() { return( <View style={styles.container}> <Text style={styles.paragraph}> Change code in the editor and watch it change on your phone! Save to get a shareable url. You get a new url each time you save. </Text> <Button theme="blue" {/* other Button component props */} /> </View> ); } } 在我的例子中,我使用定义为硬编码对象的样式.您可以向其添加API调用和套接字通信逻辑. 在示例中,不是将完整样式对象从一个组件/屏幕传递到另一个组件/屏幕,我只需简单地传递主题名称,主题道具上的任何更改都将强制组件从样式常量中获取新样式对象. 不需要为每个对象设置主题.您可以在对象中使用更高的属性. 例 const styles = { id5248698745: { button: { backgroundColor: 'green' },label: { color: 'yellow',fontSize: 18 },paragraph: { color: 'red',fontSize: 19 },headings: { color: 'wihte',fontSize: 24 } } }; // ... render() { const {style,styles[theme].button]} /> } // ... // <Button theme={this.props.themeId} {/* other Button component props */} /> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |