如何获取 refs antd 组件选择 antd 的值?

use*_*909 3 javascript components reactjs antd

我尝试使用最新版本的 antd(3.10.0) 和 react(16.5.2)。

我根据https://reactjs.org/docs/refs-and-the-dom.html使用新的 ref 方式

this.myRef = React.createRef();
Run Code Online (Sandbox Code Playgroud)

什么时候撕裂?应该像:

rend(){
                    <Select style={{ width: 200 }} ref={this.myRef}>
                    {Object.entries(this.state.catedict)
                        .map(en => <Option key={en[0]}>{en[1]}</Option>)}
                </Select>
}
Run Code Online (Sandbox Code Playgroud)

但是当我想获取 Input 或 Select 的值时

我试着:

console.log(this.myRef.current.value);
Run Code Online (Sandbox Code Playgroud)

但只会得到错误的结果。

我什至发现:

console.log(this.myRef.current);
Run Code Online (Sandbox Code Playgroud)

结果是:

t {props: {…}, context: {…}, refs: {…}, updater: {…}, saveSelect: ƒ, …}
context: {}
props: {style: {…}, children: Array(2), prefixCls: "ant-select", showSearch: false, transitionName: "slide-up", …}
rcSelect: t {props: {…}, context: {…}, refs: {…}, updater: {…}, onInputChange: ƒ, …}
refs: {}
renderSelect: ƒ (n)
saveSelect: ƒ (n)
state: null
updater: {isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_reactInternalFiber: Na {tag: 2, key: null, type: ƒ, stateNode: t, return: Na, …}
__proto__: v
Run Code Online (Sandbox Code Playgroud)

我想给出 Select 的值。我应该怎么做?

小智 5

可以通过ref获取,antd select是rc-select的hoc,如果要获取值,还是通过ref.rcSelect获取

`the react dom`
<Select ref={r => this.ctryListRef = r} />

`the js code`
console.log(this.ctryListRef.rcSelect.state.value)
Run Code Online (Sandbox Code Playgroud)

通过rcSelect.state.value,你可以得到这个值。

另外,你可以得到antd textArea 的值,这只是另外一个特例~