我的问题是这样的。我有两个组件。第一个组件是图像裁剪器。第二个组件是我应该显示裁剪图像的一个组件。状态发生变化后调用函数reactjs
我面临的问题是我可以将裁剪图像传递给我的第二个组件,但我必须按下裁剪图像并传递给第二个组件的按钮两次。在第二次点击时,只有我的图像传递给第二个组件。但我只能通过一次点击就能在第一个组件中显示裁剪后的图像。我认为这是发生的,因为在reactjs状态变化不会立即发生。那我该如何解决这个问题。
我的方法是在第一个组件中创建一个prop
函数,作为this.props.croppedImage(this.state.preview.img);
这里this.state.preview.img
是裁剪后的图像。在第二个组件中,我通过调用prop函数来获取裁剪后的图像。
我的代码
第一个部件(种植者)
class CropperTest extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "beautiful",
scale: 1,
preview: null,
}
this.handleSave = this.handleSave.bind(this);
}
handleSave =() => {
const img = this.editor.getImageScaledToCanvas().toDataURL();
this.setState({
preview: {
img,
scale: this.state.scale,
}
})
this.props.croppedImage(this.state.preview.img);
}
setEditorRef = (editor) => {
this.editor = editor
}
render() {
return (
<div>
<div className="overlay"></div>
<div className="crop_div">
<AvatarEditor
image={this.props.cropImage}
ref={this.setEditorRef}
width={450}
height={450}
border={50}
color={[255, 255, 255, 0.6]} // RGBA
scale={this.state.scale}
rotate={0}
/>
</div>
<div className="zoom_slider text_align_center">
<input className="crop_btn" type='button' onClick={this.handleSave} value='Save'/>
</div>
</div>
)
}
}
export default CropperTest;
第二组件
在这里,我基本上是做以下。
<CropperTest croppedImage = {this.getCroppedImg}/>
getCroppedImg(img){
alert("Perfect Storm");
this.setState({
previewImg:img
})
}
setState接受第二个参数作为状态更新时的回调函数。试试看! – Brian
另外,如果你声明他们像'method =()=> {0123''' – ffxsam
@ffxsam谢谢,但它不是我的问题的根源 – CraZyDroiD