React父函数调用child的嵌套componentDidMount函数?

时间:2016-08-05 23:47:11

标签: javascript d3.js reactjs

我正在使用带反应的D3,我需要在父进程运行handleClick()时运行resize函数,或者只是在切换状态改变时运行。解决这个问题的最佳方法是什么? 父组件

class Wrapper extends Component {
    constructor(props) {
        super(props);
        this.state = {
            toggle: true
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        if (!this.state.toggle) {
            this.setState({toggle: true})
        } else { 
            this.setState({toggle: false})
        }
    }
    render() {
       const toggled = this.state.toggle ? 'toggled' : '';
       return (
           <div id="wrapper" className={toggled}>
               <UnitedStatesMap />
           </div>
       );
    }
}

子组件

class UnitedStatesMap extends Component {
    constructor() {
        super();

        this.state = {
            activeState: d3.select(null)
        };
    }

    shouldComponentUpdate() {
        return false;
    }

    componentDidMount() {
        function resize() {
            if(activeState[0][0]) { reset() };
            width = document.getElementById('page-content-wrapper').offsetWidth;
            height = width * mapRatio;

            projection
                .translate([width / 2, height / 2])
                .scale(width);

            svg
                .style('width', `${width}px`)
                .style('height', `${height}px`)

            svg.select('rect')
                .attr('width', width)
                .attr('height', height)

            g.selectAll('.state').attr('d', path);
        }
        render() {
            return (
                <div id="map" ref="map"></div>
            )
        }
}

1 个答案:

答案 0 :(得分:1)

C传递<math.h>Wrapper

toggle

UnitedStatesMap添加

<UnitedStatesMap toggle={this.state.toggle} />

显然,您必须将UnitedStatesMap函数移动到自己的实例方法中,然后只需在componentWillReceiveProps(nextProps) { if (this.props.toggle !== nextProps.toggle) { // call resize } } resize中调用它。

相关问题