[英]Cannot access this.props from string to function
我想知道为什么我可以直接使用this.props
但我不能使用this.props
从string到function
。
错误是:
undefined不是一个对象(评估'this.props.navigation')
这里是我试过的示例代码:
state={
stringToFn="this.props.navigation.navigate(\'otherscreen\')",
stringToFn2="alert(\'otherscreen\')"
}
renderThis(){
let nyobaFunc = new Function("return " + "()=>{"+this.state.stringToFn+"}")();
return(
<TouchableOpacity onPress={nyobaFunc} style={styles.flatListButton}>
<CustomText style={styles.flatListSubTitle}>{'HitMe!'}</CustomText>
</TouchableOpacity>
)
}
render(){
return(
{this.renderThis()}
)
}
但是如果我将stringToFn
值直接放入onPress
,或者如果我将this.state.stringToFn
更改为this.state.stringToFn2
中的nyobaFunc
,它的工作就像一个魅力
任何人都可以帮助我为什么会发生这种情况?
您想在更改代码后尝试如下吗?
constructor(props) {
super(props);
this.state = {
stringToFn="navigate(\'otherscreen\')",
stringToFn2="alert(\'otherscreen\')"
};
...
render() {
const { navigate } = this.props.navigation;
...
let nyobaFunc = new Function('navigate',`return + ${this.state.stringToFn}`)
<TouchableOpacity onPress={() => nyobaFunc(navigate)} style={styles.flatListButton}>
尝试将此绑定到您的函数:
state={
stringToFn="this.props.navigation.navigate(\'otherscreen\')",
stringToFn2="alert(\'otherscreen\')"
}
renderThis(){
let nyobaFunc = new Function(`return ${this.state.stringToFn}`);
return(
<TouchableOpacity onPress={nyobaFunc.bind(this)} style={styles.flatListButton}>
<CustomText style={styles.flatListSubTitle}>{'HitMe!'}</CustomText>
</TouchableOpacity>
)
}
render(){
return(
{this.renderThis()}
)
}
这不是一个好习惯 - 每次渲染绑定都会创建一个新函数 - 而不是使用new Function
我建议您将此函数全部移动到带参数的常规函数中。
看起来您的navigation
道具未定义。 在调用之前添加空检查。
this.props.navigation && this.props.navigation.navigate(\'otherscreen\')
从你的评论i want to create a dynamic function, so the function getting from API, i need to convert the string of function into the function itself
我认为你想要一个解决方案,你将字符串映射到可能的函数。
import React from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
class App extends React.Component {
handlePress = () => {
const taskName = 'navigate'; // get the name of the task from api
// taskName to task mapping
switch (taskName) {
case 'navigate':
this.props.navigation.navigate('otherscreen');
break;
case 'alert':
alert('otherscreen');
break;
}
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.handlePress}>
<Text>Do API Task</Text>
</TouchableOpacity>
</View>
);
}
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.