Javascript 将html属性添加到外部组件
我正在使用一个我不能直接更改的组件,但我想扩展它Javascript 将html属性添加到外部组件,javascript,reactjs,Javascript,Reactjs,我正在使用一个我不能直接更改的组件,但我想扩展它 import { Button } from '@external-library' // Currently how the button component is being used <Button click={() => doSomething()} /> // I would like to add a tabIndex to the button <Button click={() => doSom
import { Button } from '@external-library'
// Currently how the button component is being used
<Button click={() => doSomething()} />
// I would like to add a tabIndex to the button
<Button click={() => doSomething()} tabIndex={0} />
如果不更改自定义组件的内部结构,则无法编辑自定义组件实现
// You can't add tabIndex to internal button without changing its implementation
const Button = () => <button>Click</button>;
//如果不更改内部按钮的实现,则无法将tabIndex添加到内部按钮
常量按钮=()=>单击;
在这种情况下,您可以使用所需的道具实现包装器:
const Component = () => {
return (
<div tabIndex={0}>
<Button />
</div>
);
};
const组件=()=>{
返回(
);
};
如果组件转发引用(还取决于它在实现中转发到哪个元素),则可以使用其属性:
// Assumption that Button component forwards ref
const Button = React.forwardRef((props,ref) => <button ref={ref}>Click</button>);
<Button ref={myRef}/>
// Usage
myRef.current.tabIndex = 0;
//假设按钮组件转发ref
const按钮=React.forwardRef((道具,ref)=>单击);
//用法
myRef.current.tabIndex=0;
如果不更改自定义组件的内部结构,则无法编辑自定义组件实现
// You can't add tabIndex to internal button without changing its implementation
const Button = () => <button>Click</button>;
//如果不更改内部按钮的实现,则无法将tabIndex添加到内部按钮
常量按钮=()=>单击;
在这种情况下,您可以使用所需的道具实现包装器:
const Component = () => {
return (
<div tabIndex={0}>
<Button />
</div>
);
};
const组件=()=>{
返回(
);
};
如果组件转发引用(还取决于它在实现中转发到哪个元素),则可以使用其属性:
// Assumption that Button component forwards ref
const Button = React.forwardRef((props,ref) => <button ref={ref}>Click</button>);
<Button ref={myRef}/>
// Usage
myRef.current.tabIndex = 0;
//假设按钮组件转发ref
const按钮=React.forwardRef((道具,ref)=>单击);
//用法
myRef.current.tabIndex=0;
您可以使用React refs()访问内部DOM按钮元素
最有可能的是,您使用的external lib
为按钮提供了一个ref
道具,用于传递您自己的create ref
const buttonRef=useRef(null);
然后,您可以使用按钮ref.current
添加tabIndex
,当您的数据准备好填充到like中时
useffect(()=>{
if(buttonRef&&buttonRef.current){
buttonRef.current.tabIndex=2;
}
},[props.someProperty]);
您可以使用React refs()访问内部DOM按钮元素
最有可能的是,您使用的external lib
为按钮提供了一个ref
道具,用于传递您自己的create ref
const buttonRef=useRef(null);
然后,您可以使用按钮ref.current
添加tabIndex
,当您的数据准备好填充到like中时
useffect(()=>{
if(buttonRef&&buttonRef.current){
buttonRef.current.tabIndex=2;
}
},[props.someProperty]);