diff --git a/README.md b/README.md index d12ade7e..c2d0f331 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,10 @@ interface CodePreviewProps extends SplitProps { * @default light */ theme?: ReactCodeMirrorProps['theme']; + /** + * Specifies the initial state of the source panel. + */ + sourceState?: 'hidden' | 'shown'; } ``` diff --git a/src/index.tsx b/src/index.tsx index 2b7fc5c9..d0c36079 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -109,6 +109,7 @@ const CodePreview = React.forwardRef((props, r noPreview = false, noScroll = false, bgWhite = false, + sourceState, ...otherProps } = props; const { @@ -183,6 +184,13 @@ const CodePreview = React.forwardRef((props, r setWidth(width === 1 ? '50%' : 1); setShowEdit(true); }; + // 通过状态props属性判断是否切换源码 + const isShown = sourceState === 'shown'; + useEffect(() => { + setWidth(isShown ? '50%' : 1); + setShowEdit(isShown); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isShown]); const onCopyCode = () => { copyTextToClipboard(code || '', (isCopy) => setCopied(isCopy)); setTimeout(() => setCopied(false), 2000); @@ -196,7 +204,7 @@ const CodePreview = React.forwardRef((props, r }; return ( - {!noPreview && !onlyEdit && ( + {!onlyEdit && (
((props, r .trim()} style={{ flex: 1, + display: !noPreview ? 'unset' : 'none', ...(width === 1 ? { width: '100%' } : {}), }} > diff --git a/src/useCodePreview.ts b/src/useCodePreview.ts index 418fde4c..06c900cc 100644 --- a/src/useCodePreview.ts +++ b/src/useCodePreview.ts @@ -16,13 +16,12 @@ export const getReactDOMClient = () => { }; export function useCodePreview(props: CodePreviewProps) { - const isShowEdit = props.sourceState === 'shown'; const [demoDom, setDemoDom] = useState(); const playerId = useRef(`${parseInt(String(Math.random() * 1e9), 10).toString(36)}`); const [fullScreen, setFullScreen] = useState(false); const [errorMessage, setErrorMessage] = useState(''); - const [showEdit, setShowEdit] = useState(isShowEdit); - const [width, setWidth] = useState(isShowEdit ? '50%' : 1); + const [showEdit, setShowEdit] = useState(false); + const [width, setWidth] = useState(1); const [copied, setCopied] = useState(false); const [code, setCode] = useState(props.code || ''); diff --git a/website/Example.tsx b/website/Example.tsx index d6a757ae..5680f663 100644 --- a/website/Example.tsx +++ b/website/Example.tsx @@ -27,6 +27,7 @@ const Example = () => { noScroll: false, noPreview: false, bordered: true, + sourceState: false, codeSandbox: { files: { 'sandbox.config.json': { @@ -105,6 +106,7 @@ const Example = () => { noScroll={state.noScroll} bgWhite={state.bgWhite} noCode={state.noCode} + sourceState={state.sourceState ? 'shown' : 'hidden'} editProps={{ onChange: (value) => { setState({ @@ -166,6 +168,10 @@ const Example = () => { 是否显示滚动条 `noScroll={state.noScroll.toString()}`
+ + 是否显示源码 `sourceState={state.sourceState ? 'shown' : 'hidden'}` + +
是否显示边框 `bordered={state.bordered.toString()}`