我已经看到了解决这个问题的一些麻烦的解决方案,使用refs或事件处理程序进行反应。我想知道在样式组件中是否有一个解决方案。
下面的代码显然不正确。当我的输入子组件有焦点时,我正试图找出最简单的方式来对父组件进行样式设计。这有可能使用样式组件吗?
有什么最好的方法来解决这个问题,特别是考虑到样式组件,即使它意味着依赖上述的一种反应方法?
const Parent = () => (
<ParentDiv>
<Input/>
</ParentDiv>
);
const ParentDiv = styled.div`
background: '#FFFFFF';
${Input}:focus & {
background: '#444444';
}
`;
const Input = styled.input`
color: #2760BC;
&:focus{
color: '#000000';
}
`;发布于 2018-07-12 22:42:55
看看:focus-within!我想这正是你要找的。
https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within
发布于 2017-08-30 14:29:59
// update 2022:
你可以使用:focus-within (谢谢你找出@hoodsy)
div:focus-within {
background: #444;
}<div>
<input type="text" />
</div>
support) //原始答案(带有IE和Edge )
遗憾的是,没有选择父级的方法,只基于带有纯CSS/样式组件的子级状态。虽然它是CSS4中的一个工作草案,但目前还没有浏览器支持它。More about this here。
我通常在输入字段中添加一个onFocus和onBlur属性,然后触发状态更改。在您的示例中,您有一个无状态组件。因此,可以使用innerRef从父类中添加或删除类。但我想你已经找到了这个解决方案。不过,我也会把它发出去:
const styled = styled.default;
const changeParent = ( hasFocus, ref ) => {
// IE11 does not support second argument of toggle, so...
const method = hasFocus ? 'add' : 'remove';
ref.parentElement.classList[ method ]( 'has-focus' );
}
const Parent = () => {
let inputRef = null;
return (
<ParentDiv>
<Input
innerRef={ dom => inputRef = dom }
onFocus={ () => changeParent( true, inputRef ) }
onBlur={ () => changeParent( false, inputRef ) }
/>
</ParentDiv>
);
};
const ParentDiv = styled.div`
background: #fff;
&.has-focus {
background: #444;
}
`;
const Input = styled.input`
color: #2760BC;
&:focus{
color: #000;
}
`;
ReactDOM.render( <Parent />, document.getElementById( 'app' ) );<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="app"></div>
更严格的方法是将Parent转换为类,这样就可以使用状态:
const styled = styled.default;
class Parent extends React.Component {
state = {
hasFocus: false,
}
setFocus = ( hasFocus ) => {
this.setState( { hasFocus } );
}
render() {
return (
<ParentDiv hasFocus={ this.state.hasFocus }>
<Input
onFocus={ () => this.setFocus( true ) }
onBlur={ () => this.setFocus( false ) }
/>
</ParentDiv>
);
}
};
const ParentDiv = styled.div`
background: ${ props => props.hasFocus ? '#444' : '#fff' };
`;
const Input = styled.input`
color: #2760BC;
&:focus{
color: #000;
}
`;
ReactDOM.render( <Parent />, document.getElementById( 'app' ) );<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="app"></div>
这样,您就可以更好地控制组件,并且可以更容易地决定将焦点/模糊状态传递给其他元素。
发布于 2018-07-29 18:08:02
@hoodsy谢谢,当输入集中时,它就像我下面在父div上使用的魅力一样,可以改变标签的颜色。
&:focus-within label{
color: blue;
}https://stackoverflow.com/questions/45962404
复制相似问题