主页上有2列。首先是图像网格,它将具有图像集合,而图像板将显示所选图像,但最初将具有默认图像。基于类的方式可以完美地工作,但是在使用react hooks方式时出现问题。
这是我的工作方式
reducers / images.js
const initialState = {
selectedImage: require('assets/images/image1.jpg')
};
export default function getSelectedImage(state = initialState, action) {
switch (action.type) {
case SELECT_IMAGE:
return { ...state, selectedImage: action.payload.image};
default:
return state;
}
}
imageboard / index.js
const ImageBoard = (props) => {
let canvasEl = React.useRef(null);
const [selected, setSelected] = React.useState(null)
const [canvasState, setCanvas] = React.useState(null)
const [state, _] = React.useReducer(imagesReducer, {selectedImage: require('assets/images/image1.jpg')})
const handleDeleteKey = event => {
if (event.keyCode === 46 || event.keyCode === 8) {
event.preventDefault();
console.log('canvasState', canvasState); // null i get
if (selected !== undefined) {
canvasState.remove(selected);
setSelected(undefined);
}
}
}
React.useEffect(() => {
runs once on mount
const canvasRef = new fabric.Canvas("canvas");
document.addEventListener(
"keydown",
handleDeleteKey,
false
);
canvasRef.on("object:selected", e => setSelected(e.target));
canvasRef.on("selection:cleared", e => setSelected(undefined));
setCanvas(canvasRef);
// used to show default image at initial
// setCanvasBackground(state.selectedImage, canvasRef);
}, [])
React.useEffect(() => {
// runs every time new getSelectedImage is received, including initial render
setCanvasBackground(props.getSelectedImage, canvasState);
}, [props.getSelectedImage])
const opacityChange =val => {
canvasState.backgroundImage.setOpacity(val / 100);
canvasState.renderAll();
}
const applyColor = e => {
selected.setColor(e.hex);
// canvasState is here null
canvasState.renderAll();
}
console.log('props', props)
return (
<Wrapper>
<Row>
<Column width={80}>
<CanvasWrapper>
<canvas
id="canvas"
ref={canvasEl}
width={500}
height={400}
className="z-depth-1"
/>
</CanvasWrapper>
</Column>
<Column width={20}>
<Filter
addText={addText}
addSubtitle={addSubtitle}
opacityChange={opacityChange}
applyTextFilter={applyTextFilter}
applyColor={applyColor}
applyBlur={applyBlur}
/>
</Column>
</Row>
</Wrapper>
);
}
images / index.js
const Images = props => {
const [_, dispatch] = React.useReducer(imagesReducer, []);
return (
<React.Fragment>
<Wrapper>
{images.map(image => (
<Image
key={image.id}
src={image.image}
alt={image.category}
onClick={() => dispatch({ type: SELECT_IMAGE, payload: image })}
/>
))}
</Wrapper>
</React.Fragment>
);
};
export default Images;
我已经按照要旨发布了工作代码。就像我说过的那样,类方法可行,我在canvasState being null
上没有遇到问题,但是canvasState
和选定的图像都没有在函数挂钩方法中显示。
这是双向完整代码的要旨
https://gist.github.com/MilanRgm/47c68ad9c2a5a295f32ffaab21f2bb26