我正在尝试学习反应以及如何使用第三方组件,我现在想做的就是使用从https://www.npmjs.com/package/react-native-countdown-component安装的组件
目标:
Countdown组件具有一个名为“ running”的“道具”,当我单击该组件时,我想对其进行修改。
代码:
我正在使用的代码只是使用“ expo init MyApp”创建的全新应用程序,然后粘贴了代码以导入和生成组件
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
// https://www.npmjs.com/package/react-native-countdown-component
import CountDown from 'react-native-countdown-component';
export default function App() {
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<CountDown
until={60}
size={30}
//onFinish={() => alert('Finished')}
digitStyle={{backgroundColor: '#FFF'}}
digitTxtStyle={{color: '#1CC625'}}
timeToShow={['M', 'S']}
timeLabels={{m: '', s: ''}}
showSeparator={true}
onPress={() =>
{
this.setState({running:true});
}}
running={false}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
单击该组件时,修改Countdown组件的“运行”属性的正确方法是什么?
答案 0 :(得分:2)
您可以正确开始使用状态。这次,我将使用React Hooks,它比使用传统的功能或类组件更简单。 See more
每次更新状态时,都会导致组件以新值重新呈现。
import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
// https://www.npmjs.com/package/react-native-countdown-component
import CountDown from 'react-native-countdown-component';
export default function App() {
const [isRunning, setRunning] = useState(false) //React Hooks
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<CountDown
until={60}
size={30}
//onFinish={() => alert('Finished')}
digitStyle={{backgroundColor: '#FFF'}}
digitTxtStyle={{color: '#1CC625'}}
timeToShow={['M', 'S']}
timeLabels={{m: '', s: ''}}
showSeparator={true}
//When component is pressed, updates state to true
onPress={() => { setRunning(true); }}
running={isRunning}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
答案 1 :(得分:0)
我找到了另一种方法,要求上一堂课,但是我更喜欢伊恩·斯特班·瓦斯科的答案。
我发现的解决方案是创建一个新组件,该组件将保留Countdown组件的“状态”,然后在主方法中使用MyCountdown组件,而不是直接使用Countdown组件
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
// https://www.npmjs.com/package/react-native-countdown-component
import CountDown from 'react-native-countdown-component';
export default class MyCountdown extends React.Component{
state = {
running: false
};
handleOnPress = () =>{
this.setState({running:!this.state.running});
}
render(){
return (
<CountDown
until={60}
size={30}
//onFinish={() => alert('Finished')}
digitStyle={{backgroundColor: '#FFF'}}
digitTxtStyle={{color: '#1CC625'}}
timeToShow={['M', 'S']}
timeLabels={{m: '', s: ''}}
showSeparator={true}
onPress={this.handleOnPress}
running={this.state.running}
/>
);
}
}