我在React中使用d3,并具有一些与d3相关的功能,这些功能需要访问一些d3变量/对象。调用componentWillReceiveProps()时,我需要调用这些函数之一。我提供了一个最小的示例,最重要的是注释。
class App extends Component {
constructor() {
super();
}
shouldComponentUpdate() {
return false;
}
componentWillReceiveProps(nextProps) {
/* Need to call reset() here */
}
componentDidMount() {
let svg = d3.select(this.refs.map).append('svg')
.attr('width', width)
.attr('height', height);
let g = svg.append('g')
.style('stroke-width', '.4px');
function reset() {
/* needs access to g */
g.transition()
.duration(1500)
.style('stroke-width', '.4px')
.attr('transform', '');
}
}
render() {
return (
<div id="map" ref="map"></div>
)
}
}
reset()
功能定义为组件方法this
参考reset()
this.g
获取g的值,以在不同的组件方法中使用它。样例代码:
class App extends React.Component {
constructor() {
super();
this.reset = this.reset.bind(this)
}
shouldComponentUpdate() {
return false;
}
componentWillReceiveProps(nextProps) {
this.reset();
}
componentDidMount() {
let svg = d3.select(this.refs.map).append('svg')
.attr('width', '100px')
.attr('height', '100px');
// Assigning value to `this.g` to be able use it in other methods.
this.g = svg.append("circle")
.attr("cx", 25)
.attr("cy", 25)
.attr("r", 25)
.style("fill", "purple");
}
reset() {
// After component will be mounted, you would have needed value in `this.g`.
this.g.transition()
.duration(1500)
.style("fill", "red");
}
render() {
return ( < div >
< div id = "map"
ref = "map" > < /div>
<button onClick={this.reset}>Reset</button >
< /div>
)
}
}
ReactDOM.render(<App / > , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="app"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句