如何在react-native中传递child和parent之间的数据?

时间:2017-01-13 15:29:27

标签: javascript react-native

module.exports= class APP extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      key1:'key1',
      key2:'key2'
    };
  render() {
    return (
       <View>
          <Button
             onPress={this.goToTisch}>
             1
          </Button>
          <Button
             onPress={this.goToTisch}>
             2
          </Button>
       </View>
    );
  }
}

我只是用react-native编写一个应用程序,不知道如何从子元素更新父状态。提前谢谢你

6 个答案:

答案 0 :(得分:13)

您需要从父级回传到子回调函数,然后在子级中调用它。

例如:

jQuery(document).ready(function($){
    $('#color-picker').iris({
        hide: false,
         palettes: ['#125', '#459', '#78b'],
    });

     $('#color-picker').iris({
         palettes: ['#000', '#000', '#000'],
    });
});

答案 1 :(得分:4)

要从子级调用父级方法,您可以像这样传递引用。

父类

ServiceLoader

儿童班

$(".amt").on("input", function() {
  var min = $.trim($("#min_amt").val()),
    max = $.trim($("#max_amt").val()),
    val = $.trim(this.value);
  if (val && (val.indexOf(".") !=-1 || Math.floor(val) != val || !$.isNumeric(val))) {
    alert("You can input only integers !");
    $(this).val(val.substring(0,val.length-1))
    $(this).focus();
    return
  }
  var dis = (min.length==0 || max.length==0) || ((+min) > (+max));
  $(':input[name="submitDiscount"]').prop('disabled',dis);
});

//这将调用父方法

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Min <input type="text" id="min_amt" class="amt" value="" /> 
Max <input type="text" id="max_amt" class="amt" value="" />
<input type="submit" name="submitDiscount" disabled "/>

答案 2 :(得分:3)

React一样。

您必须exchange information through props,或使用像Redux这样的库。

答案 3 :(得分:0)

使用这样的道具:

父:

<Parent>
  <Child onChange={this.change} />
</Parent>

子:

<button onclick={this.props.onChange('It Changed')} />

有了这个,你可以在父母那里做任何你想做的事。

答案 4 :(得分:0)

这可以通过两种方式实现:

父项:

//Needs argument
const addGoalHandler = goalTitle => {
        // code for updating state
}

<GoalInput onAddGoal={this.addGoalHandler} />

子组件:

方法1:使用香草Javascript

<Button 
    title="ADD"
    onPress={props.onAddGoal.bind(this, enteredGoal)}
/>

方法2:使用箭头功能

<Button 
    title="ADD"
    onPress={() => { props.onAddGoal(enteredGoal) } }
/>

答案 5 :(得分:-1)

class Parent extends Component{
   constructor(props){
   super(props);
    this.state={value:''};
    this.getData=this.getData.bind(this);
  }

  getData(val){
   console.log(val);
  this.setState({
    value:val
  });
  }
    render(){
      const {value}=this.state
    return(
      <View>
      <Screen sendData={this.getData}/>
      <View>
        <Text>
    {this.state.value};
    </Text>
      </View>
      </View>
    )
    }
}
export default Parent;


CHILD CLASS:

class Child extends Component{
   componentWillMount(){
    this.props.sendData('data');
   }
    render(){ 
    return(
        <View>  
       </View>
    )
    }  
}
export default Child;
相关问题