joj*_*ojo 5 javascript conditional attributes reactjs react-jsx
我有一个场景,我正在使用React.js使用以下代码创建一个div:
React.createElement('div', {}, "div content")
Run Code Online (Sandbox Code Playgroud)
一些额外的javascript处理将允许我演示这个div是否需要将className属性设置为"ClassA"或"ClassB",或者它是否应该没有className.
有没有办法在javascript中访问从React DOM创建的div并添加className属性?
注意:我无法实现这是JSX所以我使用了createElement方法.
编辑:值得一提的是,我可能需要有条件地添加className以外的属性.例如,我可能需要根据条件逻辑向锚标签添加"alt"属性.先感谢您.
使用JSX传播。使用道具进行构建和对象,根据您的喜好对其进行修改,然后将其传递给组件,如下所示:
const props = {
name: 'SomeName'
}
if (true) {
props.otherName = 'otherName';
}
return (
<SomeComponent {...props}/>
);
Run Code Online (Sandbox Code Playgroud)
看到那个...
语法吗?散布操作员可以完成工作-所有道具最终将成为组件上单独的属性。
看看这个小问题:http : //www.webpackbin.com/4JzKuJ9C-
cch*_*ain -1
这是 React 中很正常的情况,几乎不需要特殊处理。
注意:最好以声明方式将 props 传递到组件树中,但如果这不是一个选项,您可以绑定侦听器函数componentDidMount
并取消绑定它们,componentWillUnmount
如以下示例所示。只要他们调用 setState,你的组件的 render 函数就会被触发。
const { Component, cloneElement } = React
class Container extends Component {
constructor(props) {
super(props)
this.state = { classNames: [ 'foo' ] }
this.appendClassName = () => {
const { classNames } = this.state
this.setState({ classNames: [ ...classNames, `foo_${classNames.length}` ] })
}
}
componentDidMount() {
document.querySelector('button').addEventListener('click', this.appendClassName)
}
componentWillUnmount() {
document.querySelector('button').removeEventListener('click', this.appendClassName)
}
render() {
const { children } = this.props
const { classNames } = this.state
return <div className={classNames.join(' ')}>{children}</div>
}
}
ReactDOM.render(<Container>I am content</Container>, document.getElementById('root'))
Run Code Online (Sandbox Code Playgroud)
.foo {
font-family: monospace;
border: 1px solid rgb(100, 50, 50);
font-size: 1rem;
border-style: solid;
border-width: 1px;
width: 50vw;
height: 50vh;
margin: auto;
display: flex;
align-self: center;
justify-content: center;
align-items: center;
}
.foo.foo_1 {
font-size: 1.5rem;
background-color: rgb(200, 100, 200);
}
.foo.foo_2 {
font-size: 2rem;
border-radius: 3px 7px;
background-color: rgb(180, 120, 200);
}
.foo.foo_3 {
border-style: dashed;
background-color: rgb(175, 130, 180);
}
.foo.foo_4 {
border-width: 2px;
background-color: rgb(160, 165, 170);
}
.foo.foo_5 {
border-width: 1rem;
background-color: rgb(150, 200, 150);
}
Run Code Online (Sandbox Code Playgroud)
<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>
<button>Click me</button>
<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)
PS - 避免使用componentWillMount
,它可能会导致生命周期中的错误,并且有传言称它可能会在 React 的未来版本中被删除。始终在 中发出充满异步副作用的请求componentDidMount
并在componentWillUnmount
. 即使您没有任何可渲染的内容,最好还是渲染占位符组件,直到数据到达(快速加载的最佳选择),或者什么也不渲染。
归档时间: |
|
查看次数: |
5831 次 |
最近记录: |