我有一个问题,我想从子组件中获取值并在父组件中使用它。
这是父组件,我通过道具将值I传递给它的子项,我希望将其恢复,所以我该如何实现呢?
import React, { Component } from 'react'
import { render } from 'react-dom'
import {Row} from 'react-bootstrap';
import Rectangle from './Rectangle.js';
import '../App.css';
class Rect extends Component {
constructor(props){
super(props);
this.state={
rects:[],
img_offset: [],
rectStyle: []
};
this.unselectOtherRects = this.unselectOtherRects.bind(this);
this.getFirstState = this.getFirstState.bind(this);
}
unselectOtherRects(e, i){
alert(i)
this.getFirstState();
}
componentDidMount(){
this.getFirstState();
}
getFirstState(){
const img = this.refs.img;
var x = img.offsetLeft;
var y = img.offsetTop;
this.setState({img_offset:[x, y]});
var rects = this.props.rects;
var rectangles = [];
for (var i = 0; i < rects.length; i++) {
rectangles[i] = {
border: '1px solid white',
position : 'absolute',
width : rects[i][0] + 'px',
height : rects[i][1] + 'px',
left : x + rects[i][2] + 'px',
top : y + rects[i][3] + 'px'
};
}
this.setState({rectStyle:rectangles});
alert("Hiii")
var test = this.state.rectStyle;
for (var i = 0; i < test.length; i++) {
alert(test[i].border)
}
}
render() {
let Rectangles;
var targetRects = this.state.rectStyle;
if (targetRects.length > 0) {
Rectangles=(
<div>
{targetRects.map(function(rect, index){
return (
<Rectangle key={index} i={index} initialState={this.unselectOtherRects.bind(this, i)} coords={this.state.rectStyle[index]}></Rectangle>
)
}.bind(this))}
</div>
)
}
else{
Rectangles=(<div></div>)
}
return (
<div>
<form id="uploadimage" action="" method="post" encType="multipart/form-data">
<Row id="image_preview" className="row">
<span id="photo">
<img ref="img" id="img" src={this.props.path} />
{Rectangles}
</span>
</Row>
</form>
</div>
);
}
}
export default Rect;
我试图直接点击组件获取索引,但它不起作用,结果未定义。
这是儿童组件
import React, { Component } from 'react'
import { render } from 'react-dom'
import {Row} from 'react-bootstrap';
import '../App.css';
class Rectangle extends Component {
constructor(props){
super(props);
this.state = {
coords:this.props.coords
}
this.onRectClick = this.onRectClick.bind(this);
}
onRectClick(e){
this.props.initialState();
// var rect_style = this.state.coords;
// rect_style.border = '1px solid black';
// this.setState({coords:rect_style});
}
render() {
return (
<div onClick={this.onRectClick} style={this.state.coords}></div>
);
}
}
export default Rectangle;
答案 0 :(得分:0)
您只需将父组件中的值设置为状态,例如:
this.state = { valueControlledByChild:null };
要使子组件能够更改此状态变量,您可以在父组件中创建此函数并将其传递给子组件:
setParentState(obj) {
Object.keys(obj).forEach((key) => {
this.setState({
[key]: obj[key]
});
});
};
render() {
...
<ChildComponent setParentState={this.setStateParentState} />
}
请不要忘记在父组件构造函数中添加它:
this.setParentState = this.setParentState.bind(this);
现在,在您的子组件中,您可以通过以下方式轻松调用此方法来覆盖其值:
this.props.setParentState({
valueControlledByChild: NEW_VALUE
});
在您的父组件中,您可以引用this.state.valueControlledByChild来获取其更新值。