我的问题是这样的。我有两个组件。第一个组件是图像裁剪器。第二个组件是我应该显示裁剪图像的组件。
我面临的问题是我可以将裁剪后的图像传递到第二个组件,但我必须按下裁剪图像并传递到第二个组件的按钮两次。在第二次单击时,只有我的图像传递到第二个组件。但我只需单击一下即可在第一个组件中显示裁剪后的图像。我认为这种情况正在发生,因为在reactjs中状态变化不会立即发生。那么我该如何解决这个问题。
我的方法是创建一个prop
第一个组件中的函数为this.props.croppedImage(this.state.preview.img);
here this.state.preview.img
是裁剪后的图像。在第二个组件中,我通过调用 prop 函数来获取裁剪后的图像。
My code
第一个组件(裁剪器)
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
})
}
我认为这种情况正在发生,因为在reactjs中状态变化不会立即发生。那么我该如何解决这个问题呢?
来自React#setState https://facebook.github.io/react/docs/react-component.html#setstate,
setState(更新程序, [回调])
setState()
将组件状态的更改加入队列。
这setState
不会立即更新状态。setState()
并不总是立即更新组件。它可能会批量更新或推迟更新。这使得读书this.state
打电话后立即setState()
一个潜在的陷阱。相反,使用componentDidUpdate
or a setState
打回来(setState(updater, callback))
致电this.props.croppedImage
in the setState
回调。您将获得组件状态的更新值。在你的情况下它this.state.preview
this.setState({
preview: {
img,
scale: this.state.scale,
}
}, () => {
this.props.croppedImage(this.state.preview.img);
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)