简体   繁体   English

React Native-在同一组件中修改道具

[英]React Native - Modify a prop within the same component

I have simple questions: 我有个简单的问题:

  1. Is it possible to modify a prop (not state) within a React Native component (not from parent component)? 是否可以在React Native组件(而不是父组件)中修改prop(不是状态)?

  2. Following [1], if I want to modify a prop within the same component, how can I achieve that (or workarounds if answer in [1] is No)? 在[1]之后,如果我想在同一组件中修改道具,该如何实现(或者在[1]中的答案为“否”的情况下解决方法)?

  3. If I have the following: 如果我有以下内容:

//Parent //父

render(){
  return <View><ChildComponent propA={this.state.propA} /></View>
}

triggerChangeInParent(val) {
  this.setState({
    propA: val
  });
}

//Child (ChildComponent) //孩子(ChildComponent)

render() {
  return <View><Text>{this.props.propA}</Text></View>
}

triggerChangeInChild(val) {
  //To set props.propA here
}

Both parent and child components are allowed to modify "propA". 父组件和子组件均允许修改“ propA”。 Whoever triggers the latest will have its value taken precedence for modifying "propA" (eg if "triggerChangeInChild" is triggered after "triggerChangeInParent", then "val" from "triggerChangeInChild" will be used for "propA". 触发最新消息的人将优先使用其值来修改“ propA”(例如,如果在“ triggerChangeInParent”之后触发“ triggerChangeInChild”,则“ triggerChangeInChild”中的“ val”将用于“ propA”)。

My question is, how do we achieve that (what possible solutions/alternatives to solve this problem)? 我的问题是,我们如何实现这一目标(解决此问题的可行解决方案/替代方案)? What is the best practice/pattern? 什么是最佳做法/模式?

Thanks! 谢谢!

  1. State is mutable and props is immutable, so you can't modify the props within component. 状态是可变的,道具是不可变的,因此您不能在组件中修改道具。 Please do it outside the current component. 请在当前组件之外执行此操作。 If you're using redux, you can do it in a reducer. 如果您使用的是redux,则可以在reducer中完成。

  2. You should modify the propA on parent only, please write a method in parent, then pass it to child via prop. 您应该仅在父级上修改propA,请在父级中编写一个方法,然后通过prop将其传递给子级。 So you can call the method from child, mean that you make the change inside child. 因此您可以从child调用方法,意味着您在child内部进行更改。

    Parent

     contractor(props){ super(props) this.modifyPropsOnParent = this.modifyPropsOnParent.bind(this) } modifyPropsOnParent(){ // do your change here } render() { return <Child modifyPropsOnParent={this.modifyPropsOnParent} otherProp={yourProps} /> } 

Child can call the parent method by this.props. 子级可以通过this.props调用父级方法。 modifyPropsOnParent() modifyPropsOnParent()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM