我正在使用react和react-bootstrap和react-select。
我有一个问题,当我点击按钮就像不显示在控制台,不做任何动作。
Input.js函数组件是Hero.js函数组件的子组件。
所以hero.js是父组件,Input.js是子组件。
我的按钮在父组件(Hero.js)。
所以我使用转发ref到父到子组件在我的按钮处理程序。
我在input .js中使用反应选择输入,我想在单击按钮时集中注意力。
按钮点击后控制台也不显示
这里是Hero.js(父组件)
import React, { useState} from "react";
import "../App.css";
import Input from "./Input";
import Btnfill from "./Btnfill";
function Hero() {
const [Infocus, setInfocus] = useState();
const focusInput = () => {
console.log(Infocus.current);
Infocus.focus();
}
return (
<>
<Input
icon={Search}
cname={{ iconavailable: "input", noIcon: "input-notIcon" }}
placeholder="Search Industries"
ref={setInfocus}
/>
<Btnfill text="Search" size="larger" onClick={focusInput} />
</>
);
}
export default Hero;
Input.js
import React, { useState, useEffect} from "react";
import Select from "react-select";
const Input = React.forwardRef((props, refrence) => {
// Input select options
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" },
];
return (
<div>
<Select
defaultValue={selectedOption}
onChange={onChangeEvent}
options={options}
className={props.icon ? props.cname.iconavailable : props.cname.noIcon}
placeholder={props.placeholder}
ref={refrence}
/>
</div>
);
})
export default Input;
你想使用ref,但实际上你在你的Hero.js中做的是-你定义状态并向下传递set-state函数。
你需要做的是:
- 在Hero中定义新的ref。jsx:
const inputRef = useRef();
- 在打开按钮中单击处理程序设置焦点。为此,您需要访问ref:
const focusInput = () => inputRef.current.focus();
的当前属性。 - Pass down ref:
<Input ... ref={inputRef} />
https://codesandbox.io/s/nervous列文- 8510特遣部队