File size: 2,493 Bytes
49af559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import React, { useState, useEffect } from 'react'

interface Props {
  qiankunProps?: any
}

const App: React.FC<Props> = ({ qiankunProps }) => {
  const [globalState, setGlobalState] = useState({
    msg: '等待获取...',
    user: '',
    history: [] as string[]
  })
  const [inputValue, setInputValue] = useState('')

  useEffect(() => {
    if (qiankunProps?.onGlobalStateChange) {
      qiankunProps.onGlobalStateChange((state: any) => {
        setGlobalState(state)
      }, true)
    }
  }, [qiankunProps])

  const changeParentState = () => {
    if (!inputValue) return
    if (qiankunProps?.setGlobalState) {
      const newMsg = `[React子应用]: ${inputValue}`
      qiankunProps.setGlobalState({
        msg: newMsg,
        history: [...globalState.history, newMsg]
      })
      setInputValue('')
    }
  }

  return (
    <div style={{ padding: '15px', backgroundColor: '#fff', borderRadius: '8px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '2px solid #61dafb', paddingBottom: '10px', marginBottom: '15px' }}>
        <span style={{ fontSize: '18px', fontWeight: 'bold', color: '#61dafb' }}>React 子应用</span>
        <span style={{ fontSize: '12px', color: '#61dafb' }}>● 运行中</span>
      </div>
      
      <div style={{ marginBottom: '15px' }}>
        <p>这是 React 子应用,它通过 props 深度集成到主框架中。</p>
        
        <div style={{ background: '#f0f9ff', padding: '10px', borderRadius: '4px', margin: '10px 0', border: '1px solid #bae6fd' }}>
          <p><strong>当前全局消息:</strong> {globalState.msg}</p>
          <p><strong>当前登录用户:</strong> {globalState.user}</p>
        </div>
        
        <div style={{ display: 'flex', gap: '10px' }}>
          <input 
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyUp={(e) => e.key === 'Enter' && changeParentState()}
            placeholder="输入要发送的消息" 
            style={{ flex: 1, padding: '8px', border: '1px solid #ddd', borderRadius: '4px' }}
          />
          <button 
            onClick={changeParentState}
            style={{ backgroundColor: '#61dafb', color: '#282c34', border: 'none', padding: '8px 16px', borderRadius: '4px', cursor: 'pointer', fontWeight: 'bold' }}
          >
            发送给全员
          </button>
        </div>
      </div>
    </div>
  )
}

export default App