Skip to content

Commit 9a9bf0e

Browse files
committed
feat: customize input can forward ref
1 parent 626f339 commit 9a9bf0e

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

examples/combobox.tsx

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,14 @@ class Combobox extends React.Component {
1010
options: [],
1111
};
1212

13+
textareaRef = React.createRef<HTMLTextAreaElement>();
14+
1315
timeoutId: number;
1416

17+
componentDidMount() {
18+
console.log('Ref:', this.textareaRef);
19+
}
20+
1521
onChange = (value, option) => {
1622
console.log('onChange', value, option);
1723
this.setState({
@@ -97,7 +103,9 @@ class Combobox extends React.Component {
97103
<Select
98104
mode="combobox"
99105
style={{ width: 200 }}
100-
getInputElement={() => <textarea rows={3} />}
106+
getInputElement={() => (
107+
<textarea style={{ background: 'red' }} rows={3} ref={this.textareaRef} />
108+
)}
101109
options={[{ value: 'light' }, { value: 'bamboo' }]}
102110
allowClear
103111
placeholder="2333"

src/Selector/Input.tsx

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@ interface InputProps {
1818
onChange: React.ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement | HTMLElement>;
1919
}
2020

21+
function fillRef(node: InputRef, ref: React.LegacyRef<InputRef> | React.Ref<InputRef>) {
22+
if (typeof ref === 'function') {
23+
ref(node);
24+
} else if (typeof ref === 'object') {
25+
(ref as any).current = node;
26+
}
27+
}
28+
2129
const Input: React.RefForwardingComponent<InputRef, InputProps> = (
2230
{
2331
prefixCls,
@@ -35,19 +43,27 @@ const Input: React.RefForwardingComponent<InputRef, InputProps> = (
3543
},
3644
ref,
3745
) => {
38-
let inputNode: React.ReactElement = inputElement || <input />;
46+
let inputNode: React.ComponentElement<any, any> = inputElement || <input />;
47+
48+
const {
49+
ref: originRef,
50+
props: { onKeyDown: onOriginKeyDown, onChange: onOriginChange, style },
51+
} = inputNode;
3952

40-
const { onKeyDown: onOriginKeyDown, onChange: onOriginChange } = inputNode.props;
53+
function inputRef(node: InputRef) {
54+
fillRef(node, ref);
55+
fillRef(node, originRef);
56+
}
4157

4258
inputNode = React.cloneElement(inputNode, {
4359
id,
44-
ref,
60+
ref: inputRef,
4561
disabled,
4662
tabIndex,
4763
autoComplete: 'off',
4864
autoFocus,
4965
className: `${prefixCls}-selection-search-input`,
50-
style: { opacity: editable ? null : 0 },
66+
style: { ...style, opacity: editable ? null : 0 },
5167
role: 'combobox',
5268
'aria-expanded': open,
5369
'aria-haspopup': 'listbox',

0 commit comments

Comments
 (0)