首页 > 解决方案 > 函数未传递给子组件

问题描述

我是 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>
        );} }}

标签: javascriptreactjsreact-nativereact-navigation

解决方案


推荐阅读