javascript - 函数未传递给子组件
问题描述
我是 react native 的学习者,任何帮助都会很重要:),我开始为我的应用程序使用 react-navigation,我有一个子组件作为我的父组件的标题,这个子组件包含一个<TextInput/>
我想更新父组件更改子组件的TextInput,通常传递一个函数作为道具的值会起作用,但是由于我static navigationOptions
用来访问子组件,那不起作用,我必须设置navigation.params .state,我已经这样做了,我已经阅读了文档,我查看了这个链接https://github.com/react-navigation/react-navigation/issues/147 但它总是会出现这个错误undefined is not an object(evaluating 'params.update')
请我怎么能完成这项工作并将功能成功传递给Box
组件
盒子组件
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ""
}
}
handleChange = (e) => {
this.props.onUpdate(e.target.value);
this.setState({search: e.target.value});
}
render() {
return (
<TextInput placeholder="Search for your herbs by name,type..." value={this.state.search}
onChange={this.handleChange}
underlineColorAndroid={'transparent'}
style={BackStyles.textBox}/> ); }}
家庭组件
export default class Home extends React.Component {
onUpdate = (val) => {
this.setState({
search: val
});
let db = SQLite.openDatabase({
name: 'test.db',
createFromLocation: "~Herbo.db",
location: 'Library'
}, this.openCB, this.errorCB);
db.transaction((tx) => {
tx.executeSql("SELECT * FROM data where name like '" + this.state.search + "' ", [], (tx, results) => {
console.log("Query completed");
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
this.setState(prevState => ({
record: [...prevState.record, row],
pressed: [...prevState.pressed, false]
}));
console.log(`Record: ${row.name}`);
//this.sleep(2);
//this.setState({record: row});
}
this.setState({loader: false})
});
});
};
static navigationOptions = ({navigation}) => {
const {params} = navigation.state.params || {};
return {
headerTitle: <Box onUpdate={params.update}/>,
};
// header: null
};
componentDidMount() {
this.navigation.setParams({
update: this.props.onUpdate()
})
}
constructor(props) {
super(props);
this.state = {
record: [],
header: null,
loader: true,
pressed: {},
ar: [],
search: ''
};
let db = SQLite.openDatabase({
name: 'test.db',
createFromLocation: "~Herbo.db",
location: 'Library'
}, this.openCB, this.errorCB);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM data', [], (tx, results) => {
console.log("Query completed");
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
this.setState(prevState => ({
record: [...prevState.record, row],
pressed: [...prevState.pressed, false]
}));
console.log(`Record: ${row.name}`);
//this.sleep(2);
//this.setState({record: row});
}
this.setState({loader: false})
});
});
}
handlePressedIn = (i, value) => {
if (this.state.ar.length > 0) {
this.state.ar.map((value) => {
this.setState(prevState => {
const pressed = {...prevState.pressed};
pressed[value] = false;
return {pressed};
})
});
}
this.setState(prevState => {
if (!this.state.ar.includes(i)) {
this.setState(prevState => ({
ar: [...prevState.ar, i]
}));
}
const pressed = {...prevState.pressed};
pressed[i] = !pressed[i];
return {pressed};
});
this.props.navigation.navigate('Details', {
itemId: i + 1,
otherParam: value
});
};
errorCB(err) {
console.log("SQL Error: " + err);
}
successCB() {
console.log("SQL executed fine");
}
openCB() {
console.log("Database OPENED");
}
render() {
const herbs = this.state.record.map((herb) =>
<TouchableNativeFeedback onPress={() => this.handlePressedIn(herb.id - 1, herb.name)} key={herb.id}>
<View style={this.state.pressed[herb.id - 1] ? BackStyles.herbBox : BackStyles.herb_box}>
<Image style={BackStyles.image} source={{uri: `${herb.name.replace(/ /g, '')}`}}/>
<View style={{flexDirection: 'column',}}><Text
style={this.state.pressed[herb.id - 1] ? BackStyles.header2 : BackStyles.header}>{herb.name}</Text>
<Text
style={this.state.pressed[herb.id - 1] ? BackStyles.sub2 : BackStyles.sub}>{herb.bot}</Text></View>
</View></TouchableNativeFeedback>
);
const view = <ScrollView overScrollMode={'never'}>{herbs}</ScrollView>;
return (
<View style={BackStyles.main}>
<View style={{flex: 1}}>
{
this.state.loader ?
<ActivityIndicator animating={this.state.loader} color='#28B564' size="large"
style={BackStyles.activityIndicator}/> : <View>{view}</View>
} </View></View> ); }}
APP.js(主要组件)
import Splash from './components/Splash';
import {createStackNavigator} from 'react-navigation';
const RootStack = createStackNavigator(
{
Home: {
screen: Home,
},
Details: {
screen: Details,
},
},
{
initialRouteName: 'Home',
navigationOptions: {
headerStyle: {
backgroundColor: '#fff',
},
headerTintColor: '#28B564',
headerTitleStyle: {
fontWeight: 'bold',
},
},
}
);
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
timePassed: false,
};
}
render() {
setTimeout(() => {
this.setState({timePassed: true})
}, 4000);
if (!this.state.timePassed) {
return <View style={{flex: 1}}>
<StatusBar backgroundColor='#28B564' barStyle='light-content'/><Splash/></View>;
} else {
return (<View style={{flex: 1}}>
<StatusBar backgroundColor='#28B564' barStyle='light-content'/>
<RootStack/></View>
);} }}
解决方案
推荐阅读
- angular - Angular2 +单选按钮不可点击
- reactjs - 分组特定子组件 React
- mysql - MySQL - SELECT 和 GROUP BY 的问题
- sql-server - 将数据从临时表导入永久表时出现动态 SQL 错误
- bazel - bazel 缺少 stddef.h 和其他 Ubuntu 18.04 的依赖项声明
- angular - Angular 7 CLI ng 生成组件错误:'无法读取未定义的属性'sourceRoot'
- matlab - 快速拆分字符串
- go - 没有处理程序的 Mux 中间件
- python - 当值是 (2x2) numpy 数组时,在独立字典中添加值
- javascript - 使用 MongoDb 在 JS 中损坏的图像源