Ссылка от Dropdown.Button (и т. Д.) - PullRequest
1 голос
/ 22 октября 2019

Как я могу получить ссылку на Dropdown.Button (это antd), когда я устанавливаю ссылку на нее, она возвращает оболочку?

 parent = null;
 parentRef = node => (this.parent = node);

render(){
 return (
 <Dropdown.Button
   ref={this.parentRef}
   overlay={menu}
   type="primary"
  >
     content
 </Dropdown.Button>
 )
}

Ответы [ 3 ]

1 голос
/ 22 октября 2019

Вам необходимо использовать справочный API, useRef или React.createRef.

См. Refs and the DOM in React:

class App extends React.Component {
  buttonRef = React.createRef();

  componentDidMount() {
    console.log(this.buttonRef);
  }

  render() {
    return (
      <Dropdown.Button ref={this.buttonRef} overlay={menu} type="primary">
        content
      </Dropdown.Button>
    );
  }
}

С крючками:

const App = () => {
  const buttonRef = useRef();

  useEffect(() => {
    console.log(buttonRef);
  }, []);

  return (
    <FlexBox>
      <Dropdown.Button ref={buttonRef} menu={menu}>
        drop down
      </Dropdown.Button>
    </FlexBox>
  );
};

Edit Q-58498231-createRef

1 голос
/ 22 октября 2019

Hei,

Ознакомьтесь с React.forwardRef () здесь.

Это функция, которую вы можете обернуть в дочерний компонент, и она специально разработана длясделать возможным, чтобы родитель имел ссылку на своих детей. Должен решить вашу проблему.

Ура!

0 голосов
/ 22 октября 2019

Вы можете передать функцию cb в атрибуте ref:

 parent = null;
 parentRef = ref => (this.parent = ref);

render(){
 return (
 <Dropdown.Button
   ref={parentRef}
   overlay={menu}
   type="primary"
  >
     content
 </Dropdown.Button>
 )
}

Или с помощью ловушки useRef:

для функциональных компонентов без классов

const parentRef =React.useRef(null); 

return  (
   <Dropdown.Button
     ref={parentRef}
     overlay={menu}
     type="primary"
   >
     content
  </Dropdown.Button>
 )

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...