phpreact / component
通过php react组件化方式创建web应用
v1.1.0
2021-08-01 20:40 UTC
README
本项目旨在模仿php中的react组件
这是通过php创建组件化web应用的一种优雅的解决方案
安装
composer require phpreact/component
使用方法
要创建一个组件,只需扩展React\Component类即可
namespace React\Tag; use React\Component; class CustomComponent extends Component{ function render(){ return new div(['style'=> 'border:1px solid #eee;border-radius:4px;max-width:500px;padding:5px;margin:10px'],[ new p(['style'=> 'color:red;background:blue'], 'Hello World'), new div('Many div') ]); } }
HTML标签是通过React Component类创建的,所有HTML标签都在命名空间React\Tag下
要注册自定义HTML标签,只需调用静态函数registerTag
React\Tag::register('tag1'); React\Tag::register(['newtag1', 'newtag2']); //multiple html tags
要渲染您的应用程序
echo new CustomComponent;
我们现在可以模拟reactjs状态管理的能力。
在应用setState时有一些细微的差别,因为我们需要将js事件setState连接到php组件
注意:确保组件被HTML标签(如p、div等)包装
class CustomComponent extends Component{ var $state = ['test' => 1]; function componentDidUpdate($prevState, $currState){} //run only when there's state update function render(){ $test = $this->state->test; return new div(['style'=> 'border:1px solid #eee;border-radius:4px;max-width:500px;padding:5px;margin:10px'],[ new p(['style'=> 'color:red;background:blue'], 'Hello World',), new div('Many div'), new button(['onclick'=> "this.setState({test: ".($test+1)."})"], "set my state ($test)") ]); } }
示例完整示例
namespace React\Tag; use React\Component; include_once 'vendor/autoload.php'; //functional Component function Cars($children = [], $text){ return new div(['style'=>'display:flex'], array_map(function($v) use($text){ return new Car(['text'=> $v . $text]); }, $children)); } function Car($text = ''){ $state = \React\useState(['test'=> 1]); return new div(['onclick'=> 'this.setState(function(state){ return {test: state.test + 1}})','style'=> [ 'color'=> '#fff', 'border-style'=>'solid', 'border-radius'=> 2, 'padding'=>5, 'border-color'=> 'red', 'border-width'=> 2, 'margin' => 5, 'background'=> 'brown', 'width'=> '100%', 'text-align'=> 'center' ]], $text . ' '. $state->test); } class App extends Component{ function render(){ return [ new div(['style'=>'color:red'],'test world'), new div(['style'=>'color:red'], 'cool'), new Cars(['text'=> ' hello world'],['Volsvagen', 'Kia', 'via']), ]; } } echo new App;