如何将状态传递给组件

时间:2019-10-31 08:32:51

标签: reactjs react-native react-navigation

我在创建该示例的那个示例中创建了MExample组件

export default class MExample extends Component {

   _validate() {
          if (validateDate(this.state.choseDate).status) {
          if (validateList(this.state.list).status) {
           var list = this.state.list;
           var choseDate = this.state.choseDate;
           console.log(list+choseDate)
                this.setState({ visibleModal: null , list:[], choseDate:''})
            } else {
                alert("select list date")
             } 
           } else {
            alert("select monthly date ")
          }
      } 
 render() {
   return (
    // jsx
   )}

export default class Mnavigate extends Component {
  render() {
    return (
     <MExample list={this.state.list} choseDate = {this.state.choseDate}/>
      // can i access value like this ?
    )
  }

如何在导入该组件this.state.list的其他组件中使用this.state.choseDate<MExample here i want list and choseDate value />

2 个答案:

答案 0 :(得分:2)

<MExample list={this.state.list} choseDate={this.state.choseDate} />

并在MExample组件内部

通过访问 this.props.listthis.props.choseDate

class MExample extends React.Component{
         render(){
          console.log(this.props.list);
          return null;
        }
    }

答案 1 :(得分:0)

您可以创建属性并将其作为道具传递。

Create a component as below 



 import React, { Component } from 'react'

        class MExample  extends Component {

                   // You can access them via this.props

                validate = () => {
                 console.log(this.prop.list);
                 console.log(this.prop.choseDate);
                } 
                render() {
                   let {list,choseDate} = this.props;            

                    // your code comes here
                    return (
                        <div>

                        </div>
                    )
                }
            }

    export default MExample;

在属性中传递状态。

<MExample list={this.state.list} choseDate={this.state.choseDate} />