I have recently refactored my app from using Class components to Functional components and having issues with a few last things.
My Home.js
looks like the following (simplified):
// imports....
import { StartStopButtons } from "../components/Button";
export default ({ navigation }) => {
const [scrollEnabled, setScrollEnabled] = useState(false);
const [elapsedMilliseconds, setElapsedMilliseconds] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const [startTime, setStartTime] = useState(false);
const [stopTime, setStopTime] = useState(false);
const [isReset, setIsReset] = useState(true);
start = () => {
console.log("START");
// stuff
};
reset = () => {
console.log("RESET");
// stuff
};
stop = () => {
console.log("STOP");
// stuff
};
return (
<View style={styles.container}>
<StartStopButtons
isRunning={isRunning}
isReset={isReset}
elapsedMilliseconds={elapsedMilliseconds}
/>
</View>
);
};
My StartStopButtons
has a different look, depending of the current state, it will either display Start
, Stop
or Reset
and call the corresponding function. I am currently putting this intelligence in another file, my Button.js
file.
Button.js
:
//imports....
export const StartStopButtons = ({
isRunning,
isReset,
elapsedMilliseconds,
}) => {
if (isRunning && isReset === false) {
return (
<View>
<TouchableOpacity onPress={stop}>
<Text>Stop</Text>
</TouchableOpacity>
<TouchableOpacity onPress={pause}>
<Text>Pause</Text>
</TouchableOpacity>
</View>
);
} else {
if (elapsedMilliseconds === 0) {
return (
<TouchableOpacity onPress={start}>
<Text>Start</Text>
</TouchableOpacity>
);
} else {
return (
<TouchableOpacity onPress={reset}>
<Text>Reset</Text>
</TouchableOpacity>
);
}
}
};
Before the refactoring, I was using this.state.start
, this.state.stop
to call my start
and stop
functions, located in Home.js
.
How can I achieve that now? Is there a better approach?
question from:
https://stackoverflow.com/questions/65875874/calling-function-in-main-file-from-component 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…