我的问题是这个。我有两个组件。第一个组件是图像裁剪器。第二个组件是我应该显示裁剪图像的组件。
我面临的问题是我可以将裁剪后的图像传递给我的第二个组件,但我必须按两次裁剪图像并传递给第二个组件的按钮。在第二次单击时,只有我的图像传递给第二个组件。但是我只需单击一下就可以在第一个组件中显示裁剪后的图像。我认为它正在发生,因为在 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
})
}