Reactjs将视图相对于其他视图进行定位



我有移动开发的背景,在那里我们绘制了相对于其他布局的布局。EX:按钮A和按钮B我可以通过参考的ID,将按钮B定位在按钮A的右侧、左侧或顶部

在reactjs中有什么方法可以实现吗?通过参考A的ID,相对于按钮A显示按钮B?

Web开发略有不同。您不会将一个元素的ID引用到另一个元素来定位它们。你只需要按照你想要的方式来定位他们。

例如,如果你想把按钮A放在按钮B的左边,把按钮A像这个一样放在上面

<div>
<ButtonA />
<ButtonB />
</div>

ButtonB不知道ButtonA在左边,但它知道左边有东西。老实说,它还有更多(比如网格、flexboxes等(,但我无法一次性解释整个html/jsx和css是如何工作的,所以这是我能给你的最简单的解释。我希望它能以某种方式回答你的问题。

这是一个工作样本,试着运行它。

<h3>Button A is at the left</h3>
<div>
<button>Button A</button>
<button>Button B</button>
</div>
<br /><br />
<h3>Button B is at the left</h3>
<div>
<button>Button B</button>
<button>Button A</button>
</div>

Demo类,它有"开始"、"下面"one_answers"结束"按钮来更改位置,一个更改视图相对于其他视图的位置的示例。

/**
* This is the testing class
*/

export default class DemoComponent extends React.Component {
constructor(props) {
super(props)
this.firstRef = React.createRef();
this.secondRef = React.createRef();
this.thirdRef = React.createRef();
this.onClickStart = this.onClickStart.bind(this)
this.onClickBelow = this.onClickBelow.bind(this)
this.onClickLast = this.onClickLast.bind(this)
}
componentDidMount() {
const first = this.firstRef.current;
const second = this.secondRef.current;
const third = this.thirdRef.current;
const firstReact = first.getBoundingClientRect();
let secondReact = second.getBoundingClientRect();
const thirdreact = third.getBoundingClientRect();

let top = firstReact.top + firstReact.height;
let left = firstReact.left + firstReact.width / 2 + secondReact.width / 2;
second.style.top = `${top + 20}px`;
second.style.left = `${left}px`;
//  secondReact = second.getBoundingClientRect();
top = firstReact.top 
left = firstReact.left + (4*firstReact.width) ;
third.style.top = `${top}px`;
third.style.left = `${left}px`;

}
onClickStart(event){
//TODO
}
onClickBelow(event){
//TODO

}
onClickLast(event){
const first = this.firstRef.current;
const second = this.secondRef.current
const firstReact = first.getBoundingClientRect();
const secondReact = second.getBoundingClientRect();
const top = firstReact.top 
const left = firstReact.left + firstReact.width  + 20;
second.style.top = `${top }px`;
second.style.left = `${left}px`;
}

render() {
return (
<div>
<_row >

<_button onClick={this.onClickStart}> start </_button>
<_button onClick={this.onClickBelow}> below </_button>
<_button onClick={this.onClickLast}> end </_button>

</_row>
<_parent id="first" ref={this.firstRef} value='first' name='first'>
First
</_parent>
<_child id="second" ref={this.secondRef} value='second' name='second'>
Second
</_child>
<_child id="third" ref={this.thirdRef} value='third' name='third'>
Third
</_child>
</div>
)
}

}

最新更新