简体   繁体   English

来自另一个组件的 React Native Run 子引用方法

[英]React Native Run Child Reference Method From Another Component

I am trying to run a component method of another component.我正在尝试运行另一个组件的组件方法。 I am trying this using react ref.我正在尝试使用 react ref。 I am also following this link: https://medium.freecodecamp.org/react-changing-state-of-child-component-from-parent-8ab547436271 But my structure is a bit more complicated.我也在关注这个链接: https : //medium.freecodecamp.org/react-changed-state-of-child-component-from-parent-8ab547436271但我的结构有点复杂。

List.js列表.js

class List extends Component {

    constructor(){
        super()
        this.LoadCounterElement = React.createRef()
    }

    render(){
        return(
            <View>
                <ItemGenerator />
                <LoadCounter ref={this.LoadCounterElement}/>
            </View>
        )
    }
}

function mapStateToProps(state) {
    return {
        counter: state.counter.counter
    }
}

function mapDispatchToProps(dispatch) {
    return {
        increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
        decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
    }
}

export default connect(mapStateToProps)(List);

ItemGenerator.js项目生成器.js

class ItemGenerator extends Component {

    render() {
        return (
            <ScrollView>
                {
                    this.state.data.map((item, index) => {
                        return(<ItemList navigate={this.props.navigate} data={item} key={index}/>)
                    })
                }
            </ScrollView>
        )
    }

}

LoadCounter.js加载计数器.js

class LoadCounter extends Component {

    constructor(props) {
        super(props)
        this.state = {
            count : 0,
        }
    }

    componentDidMount() {
        this._renderCount()
    }

    _renderCount = () => {
        this.setState({count:this.props.counter})
    }

    render(){
        return(
            <View>
                <Text>{this.state.count}</Text>
            </View>
        )
    }
}

function mapStateToProps(state) {
    return {
        counter: state.counter.counter
    }
}

export default connect(mapStateToProps)(withNavigation(LoadCounter));

ItemList.js项目列表.js

class ItemList extends Component {
    render() {
        return(
            <View>
                <TouchableOpacity onPress={() => {
                    this.props.increaseCounter()
                    this.LoadCounterElement.current._renderCount()
                }}>
                    <Card containerStyle={{margin: 0}}>
                        <View style={{flex:1, flexDirection:'row', height:70, alignItems:'center', justifyContent:'space-between'}}>
                            <View style={{flexDirection:'row', alignItems:'center', width:'55%'}}>
                                <View style={{flexDirection:'column', marginLeft:10}}>
                                    <Text style={{...}}>{this.props.data.name}</Text>
                                </View>
                            </View>
                        </View>
                    </Card>
                </TouchableOpacity>
            </View>
        )
    }
}

function mapDispatchToProps(dispatch) {
    return {
        increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
        decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
    }
}

export default connect(mapStateToProps)(ItemList);

counterReducer.js counterReducer.js

const initialState = {
    counter: 1
}
const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREASE_COUNTER':
            return { counter: state.counter + 1 }
        case 'DECREASE_COUNTER':
            return { counter: state.counter - 1 }
    }
    return state
}

export default counterReducer;

As you can see in ItemLiist Component, i am trying to run _renderCount method which is in Component LoadCounter.正如您在 ItemLiist 组件中看到的那样,我正在尝试运行 Component LoadCounter 中的 _renderCount 方法。 But its not working.但它不起作用。 Kindly guide what i am missing?请指导我缺少什么?

The problem here is that you have some data in child component that should be reflected in a parent component.这里的问题是子组件中有一些数据应该反映在父组件中。 I would recommend that you move the shared state in the parent component or to the reducer state.我建议您将父组件中的共享状态移动到减速器状态。

It is odd that you are using an action creator to increment/decrement counts - which I am thinking that updates some reducer state.奇怪的是,您使用动作创建器来增加/减少计数 - 我认为这会更新一些减速器状态。 If this is the case, why store that state in the local component state again ?如果是这种情况,为什么再次将该状态存储在本地组件状态中? You could just read the counter state from the reducer in your parent component.您可以从父组件中的减速器读取计数器状态。

Parent.js

class Parent extends React.Component {
  render() {
    return (
      <div>
        <span>{this.props.count}</span>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  count: state.yourCountReducer.count,
});

export default connect(mapStateToProps)(Parent);

Child.js

class Child extends React.Component {
  render() {
    return (
      <div>
        <button onClick={() => this.props.increaseCounter()}>+</button>
        <button onClick={() => this.props.decreaseCounter()}>-</button>
      </div>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
  decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
});

export default connect(null, mapDispatchToProps)(Child);

This way, the parent component will show the updated counter state when the child component updates the count.这样,当子组件更新计数时,父组件将显示更新的计数器状态。 From your sample code, I am not sure if there is any good reason to store a shared reducer state in any component's local state.从您的示例代码中,我不确定是否有充分的理由将共享的 reducer 状态存储在任何组件的本地状态中。

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

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